select2官网:https://select2.org/
单选select默认有一个search框。多选select没有明显的search框,但是在文本框中输入的时候具有搜索效果。
可以通过定义matcher
来自定义search box的行为,当然这里的matcher只对local data有效。
function matchCustom(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') {
return data;
}
// Do not display the item if there is no 'text' property
if (typeof data.text === 'undefined') {
return null;
}
// `params.term` should be the term that is used for searching
// `data.text` is the text that is displayed for the data object
if (data.text.indexOf(params.term) > -1) {
var modifiedData = $.extend({}, data, true);
modifiedData.text += ' (matched)';
// You can return modified objects from here
// This includes matching the `children` how you want in nested data sets
return modifiedData;
}
// Return `null` if the term should not be displayed
return null;
}
$(".js-example-matcher").select2({
matcher: matchCustom
});
只有第一级的对象会经过matcher方法处理,如果你需要处理的是一个分组的select,则需要通过遍历children数组来一个个match。
This example matches results only if the term appears in the beginning of the string:
function matchStart(params, data) {
// If there are no search terms, return all of the data
if ($.trim(params.term) === '') {
return data;
}
// Skip if there is no 'children' property
if (typeof data.children === 'undefined') {
return null;
}
// `data.children` contains the actual options that we are matching against
var filteredChildren = [];
$.each(data.children, function (idx, child) {
if (child.text.toUpperCase().indexOf(params.term.toUpperCase()) == 0) {
filteredChildren.push(child);
}
});
// If we matched any of the timezone group's children, then set the matched children on the group
// and return the group object
if (filteredChildren.length) {
var modifiedData = $.extend({}, data, true);
modifiedData.children = filteredChildren;
// You can return modified objects from here
// This includes matching the `children` how you want in nested data sets
return modifiedData;
}
// Return `null` if the term should not be displayed
return null;
}
$(".js-example-matcher-start").select2({
matcher: matchStart
});
$('select').select2({
minimumInputLength: 3, // only start searching when the user has input 3 or more characters
maximumInputLength: 20 // only allow terms up to 20 characters long
});
$('select').select2({
minimumResultsForSearch: 20 // at least 20 results must be displayed
});
将minimumResultsForSearch
值设置为-1,或者Infinity
。
$("#js-example-basic-hide-search").select2({
minimumResultsForSearch: Infinity
});
设置后select中只能选择,不能输入文本
$('#js-example-basic-hide-search-multi').select2();
$('#js-example-basic-hide-search-multi').on('select2:opening select2:closing', function( event ) {
var $searchfield = $(this).parent().find('.select2-search__field');
$searchfield.prop('disabled', true);
});
var data = {
id: 1,
text: 'Barn owl'
};
var newOption = new Option(data.text, data.id, false, false);
$('#mySelect2').append(newOption).trigger('change');
The third parameter of new Option(…) determines whether the item is “default selected”; i.e. it sets the selected attribute for the new option. The fourth parameter sets the options actual selected state - if set to true, the new option will be selected by default.
// Set the value, creating a new option if necessary
if ($('#mySelect2').find("option[value='" + data.id + "']").length) {
$('#mySelect2').val(data.id).trigger('change');
} else {
// Create a DOM Option and pre-select by default
var newOption = new Option(data.text, data.id, true, true);
// Append it to the select
$('#mySelect2').append(newOption).trigger('change');
}
单选select:
$('#mySelect2').val('1'); // Select the option with a value of '1'
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed
多选select:
$('#mySelect2').val(['1', '2']);
$('#mySelect2').trigger('change'); // Notify any JS components that the value changed
When you make any external changes that need to be reflected in Select2 (such as changing the value), you should trigger this event.
对于ajax源的select2来说,不能通过.val()设置预选中状态,因为在select2被打开或者用户开始搜索前,ajax请求根本不会被发送,所以根本就没有options,更无法设置预选中状态。
因此,处理这种情况的最简单办法就是把预选中的项目作为新项目添加进来。
The best way to deal with this, therefore, is to simply add the preselected item as a new option. For remotely sourced data, this will probably involve creating a new API endpoint in your server-side application that can retrieve individual items:
// Set up the Select2 control
$('#mySelect2').select2({
ajax: {
url: '/api/students'
}
});
// Fetch the preselected item, and add to the control
var studentSelect = $('#mySelect2');
$.ajax({
type: 'GET',
url: '/api/students/s/' + studentId
}).then(function (data) {
// create the option and append to Select2
var option = new Option(data.full_name, data.id, true, true);
studentSelect.append(option).trigger('change');
// manually trigger the `select2:select` event
studentSelect.trigger({
type: 'select2:select',
params: {
data: data
}
});
});
Notice that we manually trigger the select2:select event and pass along the entire data object. This allows other handlers to access additional properties of the selected item.
$('#mySelect2').val(null).trigger('change');
方法1:
$('#mySelect2').select2('data');
返回一个js对象数组,包括选中项的所有properties/values。
方法2:
$('#mySelect2').find(':selected');
可以扩展<option>
选项,通过data-*
属性添加自定义数据。
$('#mySelect2').select2({
// ...
templateSelection: function (data, container) {
// Add custom attributes to the <option> tag for the selected option
$(data.element).attr('data-custom-attribute', data.customValue);
return data.text;
}
});
// Retrieve custom attribute value of the first selected element
$('#mySelect2').find(':selected').data('custom-attribute');
(1)打开列表(open)
$('#mySelect2').select2('open');
(2)关闭列表(close)
$('#mySelect2').select2('close');
(3)检查列表是否已初始化
if ($('#mySelect2').hasClass("select2-hidden-accessible")) {
// Select2 has been initialized
}
(4)去除select2特性(destroy)
$('#mySelect2').select2('destroy');
(5)解绑事件(.off)
去除select2特性后,只会去除自带的效果,自己手动绑定的事件,还需通过.off
手动解绑。
// Set up a Select2 control
$('#example').select2();
// Bind an event
$('#example').on('select2:select', function (e) {
console.log('select event');
});
// Destroy Select2
$('#example').select2('destroy');
// Unbind the event
$('#example').off('select2:select');
(1)事件列表
当用户在select2上执行不同操作时,select2会触发不同的事件,用户能够监听这些事件,并且添加相应的处理。
用户也可以通过.trigger
来手动触发这些事件。
Event | Description |
---|---|
change | Triggered whenever an option is selected or removed. |
change.select2 | Scoped version of change. See below for more details. |
select2:closing | Triggered before the dropdown is closed. This event can be prevented. |
select2:close | Triggered whenever the dropdown is closed. select2:closing is fired before this and can be prevented. |
select2:opening | Triggered before the dropdown is opened. This event can be prevented. |
select2:open | Triggered whenever the dropdown is opened. select2:opening is fired before this and can be prevented. |
select2:selecting | Triggered before a result is selected. This event can be prevented. |
select2:select | Triggered whenever a result is selected. select2:selecting is fired before this and can be prevented. |
select2:unselecting | Triggered before a selection is removed. This event can be prevented. |
select2:unselect | Triggered whenever a selection is removed. select2:unselecting is fired before this and can be prevented. |
(2)监听事件
$('#mySelect2').on('select2:select', function (e) {
// Do something
});
(3)通过e.params.data
获得Event Data
$('#mySelect2').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
(4)手动触发事件
你可以手动触发事件,而且还可以传递一些参数。
var data = {
"id": 1,
"text": "Tyto alba",
"genus": "Tyto",
"species": "alba"
};
$('#mySelect2').trigger({
type: 'select2:select',
params: {
data: data
}
});
(5)Limiting the scope of the change event
(6)Preventing events