Select2 - Sorting results by query

前端 未结 3 1470
天涯浪人
天涯浪人 2020-12-31 06:12

I\'m using Select2 version 4.0.0.

If my results contain multiple words, and the user enters one of those words, I want to display the results sorted by where the ent

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-12-31 07:04

    You could grab the search query from the value of the input box generated by Select2 by identifying it with the select2-search__field class. That's probably going to break across versions, but since they don't provide a hook to get the query some sort of hack will be needed. You could submit an issue to have them add support for accessing the query during sort, especially since it looks like it was possible in Select2 3.5.2.

    $('#fruit').select2({
      width: '200px',
      sorter: function(results) {
        var query = $('.select2-search__field').val().toLowerCase();
        return results.sort(function(a, b) {
          return a.text.toLowerCase().indexOf(query) -
            b.text.toLowerCase().indexOf(query);
        });
      }
    });
    
    
    
    
    

提交回复
热议问题