安装select2

  1. 下载地址:https://github.com/select2/select2/tags
  2. 引入js和css文件:
<link href="path/to/select2.min.css" rel="stylesheet" />
<script src="path/to/select2.min.js"></script>

下拉选框实现

……
<select id="select2-example" name="example" style="width:100%" >
    <option value="">请选择</option>
</select>  

……      

<script>
    var data = [{ id: 0, text: 'wechat' }, { id: 1, text: 'QQ' }];
  $(document).ready(function () {
    $("#select2-example").select2({
        data: data,
        placeholder:'请选择',
        allowClear:true //允许清除选中项
       })
  });
</script>

多级联动实例

html

<label for="province">考试省份:</label>
<select id="select2_province" class="form-control" name="province">
    <option value="" selected="selected">请选择</option>
</select>
<label for="specialty">就读专业:</label>
<select id="select2_specialty" class="form-control" name="specialty">
    <option value="" selected="selected">请选择</option>
</select>

js

<script>
    //初始化省份
    $("#select2_province").select2({
        data: [{id:1,text:"北京"},{id:2,text:"上海"},{id:3,text:"广东"}],
    });
    //选择省份事件
    $("#select2_province").on("select2:select", function (e){
        var province = $(this).val()
        resetSelect2('select2_specialty')
        selectSpecialty(province)
    })
    //重置专业下拉选框内容,否则会显示上一个省份的专业
    function resetSelect2(id){
        $("#"+id).val("").select2()
        $("#"+id).html('<option value="" selected="selected">请选择</option>')
    }
    //异步加载省份对应的专业
    function selectSpecialty(province){
        $.ajax({
            url:"route/to/get/specialty",
            type: 'post',
            dataType: 'text',
            data: {'province':province},
            success: function (response)  {
                if(response!="" && response!=null){
                    $("#select2_specialty").select2({
                        data: JSON.parse(response)
                    });
                }
            },
            error:function(){
                alert('请求错误,请稍后重试~','','error')
            }
        })
    }

</script>

注意:清除上个省份加载进来的选项数据。

刷新回显

单选回显方式:

$(".select2-example").select2('val','1')

多选回显方式:

$(".select2-example").val(['0','2']).trigger("change");
Last modification:April 9th, 2019 at 03:10 pm