Select2 drop-down box

Official website: http://select2.github.io/ 

1. The file needs to introduce select2.full.js, select2.min.css (version 4.0.1) and jquery.1.8.3 and above

In the latest version of select2, some functions cannot be used properly if the referenced jquery version is lower. For example: clear function allowClear : true 

Please use <select></select> tags for the latest version (for localized data you can use input, but for ajax remote data you must use select)

二.placeholder

placeholder placeholder prompt text, if you need to clear the function, you must set placeholder.

3. Load local data

The default data attributes of select2 are id and text. The new version can be customized, but it is better to use the default ones. Therefore, it is best to convert the provided json to the form of id and text. Of course, other attributes can be added.

var data = [{ id: 0, text: 'enhancement' }, { id: 1, text: 'bug' }, { id: 2, text: 'duplicate' }, { id: 3, text: 'invalid' }, { id: 4, text: 'wontfix' }];
$("#c01-select").select2({
  date: date,
  placeholder: 'Please choose' ,
  allowClear:true
})

4. Load remote data

$("#c01-select").select2({
  ajax: {
    url: "data.json",
    dataType: 'json',
    delay: 250,
    data: function (params) {
      return {
        q: params.term,
      };
    },
    processResults: function (data) {
      return {
        results: data
      };
    },
    cache: true
  },
  escapeMarkup: function (markup) { return markup; }, 
  minimumInputLength: 1,
  templateResult: formatRepo,
  templateSelection: formatRepoSelection
});

illustrate:

     1.q: params.term 查询参数(params.term表示输入框中内容,q发生到服务器的参数名;所以这里你可以添加自定义参数,如:stype:'person')

     2.processResults中results: data返回数据(返回最终数据给results,如果我的数据在data.res下,则返回data.res。这个与服务器返回json有关)

     3.minimumInputLength 最小需要输入多少个字符才进行查询,与之相关的maximumSelectionLength表示最大输入限制。

     4.escapeMarkup字符转义处理

     5.templateResult返回结果回调function formatRepo(repo){return repo.text},这样就可以将返回结果的的text显示到下拉框里,当然你可以return repo.text+"1";等

     6.templateSelection选中项回调function formatRepoSelection(repo){return repo.text}

     7.关于返回的 json的格式:select2默认json格式为[{id:1,text:'text'},{id:2,text:'text'}],新版严格要求这样的格式,当然你可以添加列,如:[{id:1,text:'text',name:'liu'}]

五.获取选中项

var res=$("#c01-select").select2("data")[0] ; //单选
var reslist=$("#c01-select").select2("data");    //多选
if(res==undefined)
{
     alert("你没有选中任何项");
}
if(reslist.length)
{
     alert("你选中任何项");
}

六.清空选择项和设置不可用

//清空选择
$("#c01-select").val(null).trigger("change");
$("#c01-select").val("你的placeholder").trigger("change");//或者
//如果你使用的是input标签(默认就是本地数据),你可以用
$("#c01-select").val('');来清空选项
//disabled
$("#c01-select").prop("disabled", false);//可用
$("#c01-select").prop("disabled", true);//不可用

七.启用多选

$("#c01-select").select2({
  data:data,
  multiple: true
});


八.下面简单说明新版与老版对比

1.结果回调和选中回调名称:formatResult、formatSelection(老版);templateResult、templateSelection(新版)

2.初始化:

//老版,注意如果初始化时文本框中本身没有值(为空),则不会触发该方法
initSelection: function (element, callback) { var id = $(element).val(); var data = { id: id, text: id};//这里是初始化的数据,你可以通过id来从服务器上获取(ajax),再装载进去 callback(data); }
//新版,直接给select添加option
$("#id").append(new Option("Jquery", 10001, false, true)); //或者 $("#id").append("<option value='10001'>Jquery</option>");

3.获取或设置值:select2("val")(老版);$("select").val()(新版)

推荐使用

var res = $("#id").select2("data");
//返回数组,单选就取res[0];好处是不进可以获取id、text还可以获取其他属性,如res[0].names

4.停用或启用:$("select").enable(false);(老版);$("select").prop("disabled", true);(新版)

5.主题样式:新版的样式已经更新,但如果想使用老版样式则可以设置 theme: "classic"

用得较多绑定插件有avalon、Vue等

尽量不要直接绑定到select标签上,当然本地数据的input还是可以的,在 change事件中手动赋值

 
 
$("#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();


下面是个人代码

HTML

 <td id="tdType">
    @Html.TextBox("GoodsQuestionTypeIds", " ", new { @class = "select2 form-control input-sm", @readonly = "readonly", QuestionTypeData = @entity.QuestionTypeData })
 </td> 

JS

  function initSelect2Data($ct, value) {//参数:控件JQuery对象,  初始值
            if (value == "[]") {
                $ct.removeAttr("readonly");
            }
            $ct.select2({
                placeholder: "请选择商品问题类型(多选)",
                minimumInputLength: 0,
                multiple: true,
                formatSelection: function (item) { return item.text; },         // 选择结果中的显示
                formatResult: function (item) { return item.text; },            // 搜索列表中的显示
                initSelection: function (element, callback) {

                    value = value.replace(/\"/g, "\""); // 替换ViewBag转意的双引号
                    var obj = $.parseJSON(value);
                    callback(obj);
                },
                ajax: {
                    url: "/AfterSale/GetQuestionSelect2Data",                             // 异步请求地址
                    dataType: "json",
                    async: true,
                    data: function (term, page) {
                        return { "term": term };
                    },
                    results: function (data, page) { return data; },            // 构造返回结果
                    escapeMarkup: function (m) { return m; }                    // 字符转义处理
                }
            });
        }

JS添加克隆行

    //添加按钮复制行事件
        function trAdd(btn) {
            var $btn = $(btn);
            var newTr = $btn.parent().parent().clone();

            //克隆行内容初始化
            newTr.find('#GoodsQuestionManageId').val('0');
            newTr.find('#QuestionQuantity').val('');
            newTr.find('#Remarks').val('');
            newTr.find('#tdType').html($('<input type="text" id="GoodsQuestionTypeIds" name="GoodsQuestionTypeIds" value=" " class="select2 form-control input-sm" />'));
            newTr.insertAfter($btn.parent().parent());//把克隆行插入到当行后
            initSelect2Data(newTr.find('input[name=GoodsQuestionTypeIds]'), '[]');
        }

JS页面加载后给所有select2框事件

  // 初始化select2控件
            $("input[name=GoodsQuestionTypeIds]").each(function (i) {
                var $ct = $(this);
                var value = $ct.attr("QuestionTypeData");//初始化多选补全框的数据源,查找输入的数据来源于ajax
                initSelect2Data($ct, value);

            });

后台:循环构建初始化数据

  foreach (GoodsQuestionManageModel model in list)
            {
                string strTypeIds = "," + model.GoodsQuestionTypeIds.Trim(',') + ",";
                var listTypeData = questionTypeData.OrderBy(q => q.GoodsQuestionTypeId).Where(q => strTypeIds.Contains("," + q.GoodsQuestionTypeId + ","))
                              .Select(q => new { id = q.GoodsQuestionTypeId, text = q.TypeName });
                model.QuestionTypeData = JsonConvert.SerializeObject(listTypeData);
            }

后台:构建查询ajax数据

      public string GetQuestionSelect2Data(string term)
        {
            string result = string.Empty;
            var list = goodsQuestionManageService.GetQuestionTypeList().Where(q => q.TypeName.Contains(term.Trim()))
                   .Select(q => new { id = q.GoodsQuestionTypeId, text = q.TypeName });
            result = "{\"results\":" + JsonConvert.SerializeObject(list) + "}";

            return result;
        }


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325897793&siteId=291194637