Select2 使用指南

2,311 阅读1分钟

使用

select2.github.io/select2/ 需要引用Jqeury

<!-- 加载 Jquery -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

<!-- 加载 Select2 -->
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.8/js/select2.min.js"></script>

初始化

  • placeholder : 占位提示文字,如果需要清除功能,则必须设置placeholder。
  • allowClear: true, 显示清除按钮
  • minimumResultsForSearch: -1 ,至少有多少条数据才显示搜索框。 -1隐藏搜索框
  • minimumInputLength:1 至少输入多少字符,开始搜索
  • maximumInputLength 最多输入的字符数
  • 多选。multiple: true 或 只需要在select标签中添加multiple="multiple"
  • maximumSelectionLength:3, 最多能选几个
  • closeOnSelect: 是否选中后关闭选择框,默认true
  • templateResult 选项回调,可修改option的内容
  • templateSelection 选中回调,选中后选择框显示的内容
  • tags: true, // 根据搜索框创建option
  • separator: ",", // 分隔符
  • matcher 匹配输入的选项
$("#zrxqid").select2({
    placeholder: {
        id: '',
        text: '--请选择--'
    },
    allowClear: true,
    minimumResultsForSearch: -1,
    minimumInputLength:1,
    templateResult: function(data){
        return data.organname + "(" + data.organcode + ")";
    },
    matcher: function(term, text, opt) {
       return text.toUpperCase().indexOf(term.toUpperCase())>=0
           || opt.attr("alt").toUpperCase().indexOf(term.toUpperCase())>=0;
    },
    ajax: {
       type:"post",
       url:“",
       data:function (params) {
           return {
              name: params.term, // 输入框中输入的内容
              page: params.page,
              jyjd:"3"
           };
       },
       dataType: 'json',
       delay: 500, // 延迟多少毫秒再请求数据
       processResults: function (data) {
            data = $.map(data, function (obj) {
            obj.id = obj.organid;
            obj.text = obj.organname + "(" + obj.organcode + ")";
                return obj;
            });
            return {
                results: data
            };
       }
});
  • 获取选中的值 $('#id_select2').select2('val')
  • 获取选中的对象 $("#id_select2").select2("data")
  • 获取选中option的text值,以下代码中的[0]用来获取第一个对象,对单选合适,如果是多选的话需要循环获取 $("#id_select2").select2("data")[0].text
  • 初始化选中值 ("#id_select2").val(2).trigger("change"); // 单选("#id_select2").val([2,3,5]).trigger("change"); // 多选 ("#id_select2").val(null).trigger('change'); // 清空("#id_select2").prop('disabled',true); // 禁用