I downloaded Select2 jquery plug in and have it all set up - I have a basic dropdown here.
<SELECT NAME="GENDER">
<OPTION VALUE="1">MALE
<OPTION VALUE="2">FEMALE
<OPTION VALUE="3">UNDEFINED
</SELECT>
I applied the plug in and it works - not a problem.
I've been reviewing the select2 documentation and what I'm trying to do is instead of searching by gender such as typing Female and Male, etc - I want the user to simply press 1 thus it brings up Male, 2 for Female.
Has anyone attempted this in select2?
I took @Tessa's great answer above and made it work with 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;
}
The parameters for the "matcher" option has changed since this has been answered. I came across this same issue when implementing a US State dropdown and each option was like <option value="PA">Pennsylvania</option>
and I wanted users to be able to either spell the state or simply type their code and it'd work. Based on the updated documentation, I modified it like this:
$('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;
}
});
Here is a working CodePen demo I whipped up that demonstrates this using both the OP's select field and a select field of the U.S. states.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With