<!--[多選]則需要加上屬性:multiple="multiple" --> <select class="form-control" id="select2-id" multiple="multiple"> <option value="1" data-plantform="android">APP1</option> <option value="1" data-plantform="ios">APP2</option> </select>
| 載入select2
var formatState = function (state) { //console.log(state); if (!state.id) { return state.text; } var $state = $('<span><img src="/public/images/'+state.element.dataset.plantform+'.jpg" style="width:25px;" /> ' + state.text + '</span>'); return $state; } $("#select2-id").select2({ templateResult : formatState, // 列表帶圖片 templateSelection : formatState, // 選中的帶圖片 language: "zh-CN", //設置 提示語言 width: "100%", //設置下拉框的寬度 placeholder: "請選擇", // 空值提示內容,選項值為 null //placeholder: {id: '', text: "請選擇"}, // 同上,這里默認空值為 '' minimumInputLength: 10 //最小需要輸入多少個字符才進行查詢 allowClear: true, //是否允許清空選中 tags: false, //設置必須存在的選項 才能選中,設置不存在的值則為null,如果 placeholder: {id: '', text: "請選擇"} 則為 '' selectOnClose: true, // 如果沒有手動選中,下拉框消失后會自動選中被hover的選項 (不建議使用) closeOnSelect: false, // 選擇后下拉框不會關閉(單選-不建議使用) minimumResultsForSearch: Infinity, // 隱藏搜索框 theme: "classic", // 樣式 maximumSelectionLength: 3, // 多選 - 設置最多可以選擇多少項 tokenSeparators: [',', ' '], // 多選 - 輸入逗號和空格會自動完成一個選項 前提是:tags: true });
| 移除select2
$("#select2-id").select2("destroy");
| 清空下拉框列表值
$("#select2-id").empty();
| 設置下拉列表
// 單選 - 必須有一項為空值,否則默認選擇第一項(如果必須選擇一項可以不設置空值) $("#select2-id").append($("<option>", {value: '', text: '全部'})); $("#select2-id").append($("<option>", {value: 'value1', text: 'text1'})); $("#select2-id").append($("<option>", {value: 'value2', text: 'text2'})); // 多選 - 不能有一項為空值,否則再清空時會出BUG $("#select2-id").append($("<option>", {value: 'value1', text: 'text1'})); $("#select2-id").append($("<option>", {value: 'value2', text: 'text2'}));
| 賦值說明:賦值會觸發change事件
// 賦值 - 單選 $("#select2-id").val('value').trigger("change"); // 賦值 - 多選 $("#select2-id").val(['value1','value2']).trigger("change");
| 獲取選中值
// 多選返回數組,單選返回字符串 $("#select2-id").val();
Select2使用示例地址:
https://select2.github.io/examples.html
Select2參數文檔說明: https://select2.github.io/options.html
Select2源碼:
https://github.com/select2/select2
