Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Search on select attribute in select2

Is it possible to search on a combination of the text and another attribute in select2? For example, can the user search on both the value of "data-test" and text below:

<option value="185" data-test="5">Test</option>
<option value="186" data-test="6">Test 2</option>
<option value="187" data-test="7">Test 3</option>

Such that searching for "Test 2" and "6" show the same single option?

This is on a list bound at the page load, so it can't be filtered elsewhere.

Thanks -

like image 326
James F Avatar asked Oct 12 '25 12:10

James F


1 Answers

It's simple enough once found -

Create a custom matching function, similar to "matcher" in select2.js:

function customMatcher(params, data) {
    // Always return the object if there is nothing to compare
    if ($.trim(params.term) === '') {
        return data;
    }

    ... OTHER MATCHING CODE


    // Check if the text contains the term
    if (original.indexOf(term) > -1) {
        return data;
    }

    // Check if the data occurs
    if ($(data.element).data('test').toString().indexOf(params.term) > -1) {
        return data;
    }

    // If it doesn't contain the term, don't return anything
    return null;
}

I added the "data('test')" to the function above and updated the initialization to:

    $("#ddl").select2({
        matcher: customMatcher
    });

Works great.

like image 186
James F Avatar answered Oct 15 '25 05:10

James F