Search code examples
jquery-select2optgroup

Display result matching optgroup using select2


I'm using select2 with Bootstrap 3. Now I would like to know whether it is possible to display all optgroup items if the search matches the optgroup name while still being able to search for items as well. If this is possible, how can I do it?


Solution

  • Actually found the solution by modifying the matcher opt

     $("#myselect").select2({
        matcher: function(term, text, opt){
             return text.toUpperCase().indexOf(term.toUpperCase())>=0 || opt.parent("optgroup").attr("label").toUpperCase().indexOf(term.toUpperCase())>=0
        }
    });
    

    Under the premise that the label attribute has been set in each optgroup.