我下载了Select2 jquery插件,并将其全部设置好--这里有一个基本的下拉列表。
<SELECT NAME="GENDER">
<OPTION VALUE="1">MALE
<OPTION VALUE="2">FEMALE
<OPTION VALUE="3">UNDEFINED
</SELECT>我把插头插进去了,它起作用了-没问题。
我一直在查看select2文档,我想要做的不是按性别搜索,比如键入女性和男性等等--我希望用户只按1,这样就可以生成男性,而女性则是2。
有人在select2上尝试过吗?
发布于 2014-06-03 17:41:43
查看文档中的"matcher“选项:http://ivaynberg.github.io/select2/#documentation
重写matcher函数,以检查给定选项的text()和val()。未经测试的示例:
$('select').select2({
matcher: function(term, text, option) {
return text.toUpperCase().indexOf(term.toUpperCase())>=0 || option.val().toUpperCase().indexOf(term.toUpperCase())>=0;
}
});发布于 2017-12-07 14:33:08
"matcher“选项的参数在回答后发生了变化。。在实现一个美国国家下拉列表时,我遇到了同样的问题,每个选项都类似于<option value="PA">Pennsylvania</option>,我希望用户能够拼写状态,或者只需键入他们的代码就可以了。根据更新的文档,我对其进行了如下修改:
$('select').select2({
matcher: function(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` is the user's search term
// `data.id` should be checked against
// `data.text` should be checked against
var q = params.term.toLowerCase();
if (data.text.toLowerCase().indexOf(q) > -1 || data.id.toLowerCase().indexOf(q) > -1) {
return $.extend({}, data, true);
}
// Return `null` if the term should not be displayed
return null;
}
});使用OP的select字段和美国各州的select字段演示这一点的下面是我制作的一个CodePen演示。
发布于 2018-10-24 23:49:11
我在上面采纳了@Tessa的好答案,并让它与optGroup一起工作。
function(params, option) {
// If there are no search terms, return all of the option
var searchTerm = $.trim(params.term);
if (searchTerm === '') { return option; }
// Do not display the item if there is no 'text' property
if (typeof option.text === 'undefined') { return null; }
var searchTermLower = searchTerm.toLowerCase(); // `params.term` is the user's search term
// `option.id` should be checked against
// `option.text` should be checked against
var searchFunction = function(thisOption, searchTerm) {
return thisOption.text.toLowerCase().indexOf(searchTerm) > -1 ||
(thisOption.id && thisOption.id.toLowerCase().indexOf(searchTerm) > -1);
};
if (!option.children) {
//we only need to check this option
return searchFunction(option, searchTermLower) ? option : null;
}
//need to search all the children
option.children = option
.children
.filter(function (childOption) {
return searchFunction(childOption, searchTermLower);
});
return option;
}https://stackoverflow.com/questions/24021276
复制相似问题