I have a select2 in my rails app for customer names, now the search feature works well with customer names as option's text are set to customer name, now I want the select2 to perform the search for customer's contact_no too. And I am setting customer's contact_no in data-attr in each option tag. So, how the searching can be performed from the data-attr in addition with the option text. Thanks in advance.
Edit Here is the HTML
<select>
<option value="1" data-contact-no="9898989898">Zamir</option>
<option value="2" data-contact-no="6767676767">Manihar</option>
<option value="2" data-contact-no="666666">Zimmie</option>
</select>
and JavaScript
$("select").select2();
I have found the solution, just initialize the select2 as:
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 || data.element.getAttribute('data-contact-no').indexOf(params.term) > -1) {
var matchedData = $.extend({}, data, true);
// You can return matched objects from here
return matchedData;
}
// Return `null` if the term should not be displayed
return null;
}
$("select").select2({
matcher: matchCustom
});
Any other solution would be appreciated. Thank You
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.