强大的下拉框插件Select2

每个人都是他人生的主角, 可是一旦沦为配角,就是他最伤心的时候。
select2是一个可以给你定制支持搜索、标签、远程数据集,无限滚动,以及其他常用功能的一个下拉框美化插件。总之,功能很强大。 ### 配置
1
2
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.2/js/select2.min.js"></script>

基本使用

1
2
3
<script type="text/javascript">
$('select').select2();
</script>

单选框

1
2
3
4
5
6
7
8
9
10
11
<script type="text/javascript">
$(document).ready(function() {
$(".js-example-basic-single").select2();
});
</script>

<select class="js-example-basic-single">
<option value="AL">Alabama</option>
...
<option value="WY">Wyoming</option>
</select>

多选框

1
2
3
4
5
6
7
8
9
<script type="text/javascript">
$(".js-example-basic-multiple").select2();
</script>

<select class="js-example-basic-multiple" multiple="multiple">
<option value="AL">Alabama</option>
...
<option value="WY">Wyoming</option>
</select>

提示信息

1
2
3
4
5
6
7
$(".js-example-placeholder-single").select2({
placeholder: "Select a state",
allowClear: true //可以删除
});
$(".js-example-placeholder-multiple").select2({
placeholder: "Select a state"
});

加载数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<script type="text/javascript">
var data = [
{ id: 0, text: 'enhancement' },
{ id: 1, text: 'bug' },
{ id: 2, text: 'duplicate' },
{ id: 3, text: 'invalid' },
{ id: 4, text: 'wontfix' }];
$(".js-example-data-array").select2({
data: data
})
$(".js-example-data-array-selected").select2({
data: data
})
</script>
<select class="js-example-data-array"></select>
<select class="js-example-data-array-selected">
<option value="2" selected="selected">duplicate</option>
</select>

加载远程数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});

禁用模式

1
2
3
4
5
6
7
8
$(".js-programmatic-enable").on("click", function () {
$(".js-example-disabled").prop("disabled", false);
$(".js-example-disabled-multi").prop("disabled", false);
});
$(".js-programmatic-disable").on("click", function () {
$(".js-example-disabled").prop("disabled", true);
$(".js-example-disabled-multi").prop("disabled", true);
});

禁用结果

1
2
3
4
5
<select class="js-example-disabled-results">
<option value="one">First</option>
<option value="two" disabled="disabled">Second (disabled)</option>
<option value="three">Third</option>
</select>

限制个数

1
2
3
$(".js-example-basic-multiple-limit").select2({
maximumSelectionLength: 2
});

隐藏搜索框

1
2
3
$(".js-example-basic-hide-search").select2({
minimumResultsForSearch: Infinity
});

DOM事件

1
2
3
4
5
6
7
8
9
change //选中或删除触发
select2:open //下拉框打开触发
select2:opening //下拉框打开之前
select2:close //下拉框关闭
select2:closing //下拉框关闭之前
select2:select //选中结果触发
select2:selecting //选中之前
select2:unselect //结果未选中
select2:unselecting //结果未选中之前
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
var $eventLog = $(".js-event-log");
var $eventSelect = $(".js-example-events");
$eventSelect.on("select2:open", function (e) { log("select2:open", e); });
$eventSelect.on("select2:close", function (e) { log("select2:close", e); });
$eventSelect.on("select2:select", function (e) { log("select2:select", e); });
$eventSelect.on("select2:unselect", function (e) { log("select2:unselect", e); });
$eventSelect.on("change", function (e) { log("change"); });
function log (name, evt) {
if (!evt) {
var args = "{}";
} else {
var args = JSON.stringify(evt.params, function (key, value) {
if (value && value.nodeName) return "[DOM node]";
if (value instanceof $.Event) return "[$.Event]";
return value;
});
}
var $e = $("<li>" + name + " -> " + args + "</li>");
$eventLog.append($e);
$e.animate({ opacity: 1 }, 10000, 'linear', function () {
$e.animate({ opacity: 0 }, 2000, 'linear', function () {
$e.remove();
});
});
}

自定义控制

1
2
3
4
5
6
7
8
9
var $example = $(".js-example-programmatic").select2();
var $exampleMulti = $(".js-example-programmatic-multi").select2();
$(".js-programmatic-set-val").on("click", function () { $example.val("CA").trigger("change"); });
$(".js-programmatic-open").on("click", function () { $example.select2("open"); });
$(".js-programmatic-close").on("click", function () { $example.select2("close"); });
$(".js-programmatic-init").on("click", function () { $example.select2(); });
$(".js-programmatic-destroy").on("click", function () { $example.select2("destroy"); });
$(".js-programmatic-multi-set-val").on("click", function () { $exampleMulti.val(["CA", "AL"]).trigger("change"); });
$(".js-programmatic-multi-clear").on("click", function () { $exampleMulti.val(null).trigger("change"); });

标签支持

1
2
3
$(".js-example-tags").select2({
tags: true
})

自动标记

当我们输入值匹配成功后 键入空格就会自动标签化

1
2
3
4
$(".js-example-tokenizer").select2({
tags: true,
tokenSeparators: [',', ' ']
})

自定义查找匹配

1
2
3
4
5
6
7
8
9
10
11
12
function matchStart (term, text) {
if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
return true;
}
return false;
}
$.fn.select2.amd.require(['select2/compat/matcher'],
function (oldMatcher) {
$(".js-example-matcher-start").select2({
matcher: oldMatcher(matchStart)
});
});

其他

关于select2的CDN资源整理:http://www.bootcdn.cn/select2/

1
2
3
4
5
<link href="http://libs.baidu.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script src="http://libs.baidu.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>
<script src="http://cdn.bootcss.com/select2/4.0.2/js/select2.js"></script>
<link href="http://cdn.bootcss.com/select2/4.0.2/css/select2.css" rel="stylesheet" />

示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<select id="sel_menu2" multiple="multiple" name="tags" class="form-control">
<optgroup label="选择标签">
<option value="1">用户管理</option>
<option value="2">角色管理</option>
<option value="3">部门管理</option>
<option value="4">菜单管理</option>
</optgroup>
</select>
<script type="text/javascript">
//多选
$("#sel_menu2").select2({
tags: true,
maximumSelectionLength: 5 //最多能够选择的个数
});
</script>

https://www.bandari.net/blog/14
https://stackoverflow.com/questions/14577014/select2-dropdown-but-allow-new-values-by-user
https://my.oschina.net/corwien/blog/672858