一、效果图


二、代码
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title></title>
</head>
<body><link href="/js/select2.min.css" rel="stylesheet" /><script src="https://code.jquery.com/jquery-3.6.0.min.js"></script><script src="/js/select2.min.js"></script><div><label style="width: 100px; font-size: 14px;">单选</label><select id="sel_menu" style="width: 400px;"><option value=""></option></select></div><div style="margin-top: 20px;"><label style="width: 100px; font-size: 14px;">多选</label><select id="sel_menu2" multiple="multiple" style="width: 400px;"></select></div><div style="margin-top: 20px;"><label style="width: 100px; font-size: 14px;">多选(含选中项)</label><select id="sel_menu3" multiple="multiple" style="width: 400px;"></select></div><button onclick="getSelectedData()" style="margin-top: 20px;">多选选中值</button>
</body>
</html><script>//下拉框数据var initdata = ["Java", "JavaScript", "C++", "C#", "Python", "PHP"];//选中数据var selectedData = [];//初始化页面加载$(document).ready(function () {//初始化select2单选initSelect2WithSearch();//初始化select2多选(没有选中项)initSelect2();//初始化select2多选(包含选中项)select2WithData(selectedData);});/* 初始化select2单选,默认带搜索功能 */function initSelect2WithSearch() {$("#sel_menu").select2({tags: true,placeholder: '请搜索或选择语言',data: initdata,allowClear: true});}/* 初始化select2多选(没有选中项)*/function initSelect2() {$("#sel_menu2").select2({tags: true,maximumSelectionLength: 5,placeholder: '请添加或选择语言',multiple: true,maximumInputLength: 10,//允许长度 data: initdata,});}/* 初始化select2多选(包含选中项)*/function select2WithData(selectedData) {$("#sel_menu3").select2({tags: true, //支持新增,默认为falsemaximumSelectionLength: 6, //最多能够选择的个数multiple: true, //支持多选,默认为falsedata: initdata, //下拉框绑定的数据allowClear: true, //支持清空,默认为falseplaceholder: '请添加或选择语言' //提示语}).val(selectedData).trigger('change'); //多选情况下给选中项的赋值}/* 获取多选框选中项的值 */function getSelectedData() {var mulSelData = $("#sel_menu3").val().join(",");//获取多选输入框选中值的方式alert("sel_menu3的选中项是:" + mulSelData);}
</script>