Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use matcher in select2.js v.4.0.0+?

Tags:

select2

If I understand correctly, the correct use of matcher before v4.0.0 was:

$('#myselect').select2({
    ...
    matcher: function(term, text) {
        // return true if matches, false if not
    }
})

With 4.0.2 this doesn't work - AFAICT there is only one parameter to matcher, which is an object. I could use the same function signature and wrap it on oldWrapper, but I would like to avoid that... I was unable to find any example or docs. So, how do I use the new matcher? Or at least, what is the function signature?

like image 864
johndodo Avatar asked Apr 13 '16 07:04

johndodo


People also ask

How do I assign a value to Select2?

New options can be added to a Select2 control programmatically by creating a new Javascript Option object and appending it to the control: var data = { id: 1, text: 'Barn owl' }; var newOption = new Option(data.text, data.id, false, false); $('#mySelect2').append(newOption).trigger('change');

How does Select2 search work?

When users filter down the results by entering search terms into the search box, Select2 uses an internal "matcher" to match search terms to results. You may customize the way that Select2 matches search terms by specifying a callback for the matcher configuration option.

What does Select2 () do?

Select2 gives you a customizable select box with support for searching, tagging, remote data sets, infinite scrolling, and many other highly used options.

Does Select2 work on mobile?

So it is advisable to use Select2 if you want to use “extended select-boxes” on mobile.


1 Answers

Found it: https://github.com/select2/select2/blob/master/src/js/select2/defaults.js (search for function matcher).

Basically, the function signature is:

matcher: function (params, data) {
    // should return:
    // - null if no matches were found
    // - `data` if data.text matches params.term
}

My problem however was connected to the fact that "text" is a hardcoded field name - I was of course using something else. Hope it helps someone.

like image 112
johndodo Avatar answered Jan 03 '23 15:01

johndodo