bootstrap select2 参数详解

<!--[多选]则需要加上属性: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="25px;" /> '
+ state.text + '</span>');


return $state;
}

$("#select2-id").select2({
     templateResult : formatState, // 列表带图片
     templateSelection : formatState, // 选中的带图片

     language: "zh-CN", //设置 提示语言
      "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
 
原文地址:https://www.cnblogs.com/cloudshadow/p/bootstrap_select2.html