B
B
Bogdan Gerasimenko2020-05-07 18:39:18
JavaScript
Bogdan Gerasimenko, 2020-05-07 18:39:18

How to force Select2 to search in data attributes?

I'm using the latest version 4.0.12 of the Select2 script.

My dropdown looks like this:

<select id="langselect">
    <option data-lang="Английский">English</option>
    <option data-lang="Русский">Russian</option>
</select>

I use matcherto search by first letter:

function matchStart(term, text) {
    if (text.toUpperCase().indexOf(term.toUpperCase()) == 0) {
        return true;
    }
    return false;
}
$.fn.select2.amd.require(['select2/compat/matcher'], function(oldMatcher) {
    $("#langselect").select2({
        matcher: oldMatcher(matchStart),
    });
});

I need to change the function matchStart()to be able to search on data-* attributes as well. I am trying to write code like this:

if ($(data.element).data('lang').toUpperCase().indexOf(term.toUpperCase()) == 0) {
    return true;
}

But an error pops up Cannot read property 'indexOf' of undefined, toString() does not help. I suppose the code should look different, but I don't know how. Please help fix the error.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dubolom Unicellular, 2020-05-07
@duboloms

https://select2.org/configuration/data-attributes
Changed:
Where did you get the data from ? Add to the list of function arguments
function matchStart( data , term, text) { ... }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question