Search code examples
jquery-select2jquery-select2-4

"select2" Add constant option


I am currently using Select2 in a project and would like to add a option to my select list that shows up regardless of what the user types or searches. The idea is to have a "Add new" option always present in the list. I do not think my code is necessary here (but if needed I may provide) as the only thing i'm lacking knowledge in this specific topic is on how to keed the option always showing. I thought of using the matcher attribute, but i'm not sure how.


Solution

  • I've managed to do it setting a new matcher, the problem was I was not sure on how to create a new matcher and still use the select2 default one. Something else I was missing was the full version of select2.

    function newMatcher(term, text){
        //The "ADD NEW" String is the text in the option I want to always show up.
        //The code after OR looks for the actual results for the user's search
        if ((text.toUpperCase().indexOf("ADD NEW") > -1)
           || (text.toUpperCase().indexOf(term.toUpperCase()) > -1)) {
             return true;
        }
    }
    $(document).ready(function() {
        $.fn.select2.amd.require(['select2/compat/matcher'], function (oldMatcher) {
            $('select').select2({
                matcher: oldMatcher(newMatcher)
            })
        })
    });