Select2 type for choice

I am trying to use select2 to display a dropdown with multiple selections, but something is wrong.

Usually, when you enter an out option, it is highlighted so that you can press Enter and select it. It underlines the option but does not highlight it, so if I type "alabama" but press "Enter", it chooses "arkansas".

I am using the latest version (3.5.1)

Html

<label class="control-label" for="states">States:</label>
<input id="states" name="states" />
<input class="btn btn-primary" type="submit" value="Submit Search" />

      

JavaScript:

$("#states").select2({ 
    width: 'resolve',
    maximumSelectionSize: 5,
    ajax: {
        dataType:"json",
        url:"getStates.cfm",
        results: function(data) {
            return {results:data};
        }
    },
    multiple:true
});

      

Am I missing some parameter? I could have sworn it worked fine the last time I used it. There are no errors in the console and it clicks fine.

Please note that the github page works just the way I want (as you type, it picks the first option that matches) enter image description here

+3


source to share


2 answers


In Select2 3.x, the highlighted result in the dropdown will always be the first result during the search. This will change in Select2 4.x, so the selected option will be selected if present.

You are looking for results to sort in different ways. By default, Select2 orders options in the order they have in the DOM, not according to their relevance. The documentation provides an example on how to customize the sorting of results using a parameter sortResults

.



Keep in mind that it is more efficient to sort the results server-side when using AJAX, so Select2 no longer does the sorting. This explains why Arkansas is returning when looking for Alabama.

+3


source


I had the same problem. And the solution was found when I found that every time I type in the search box, every time it calls a function query

. It. This way, all I had to do was fill in the results only if it matches at least one character in any text of the available options. The next way:



query  : function(opts){
  var res = [];
  var fulloptions = ArrayFoundUponYourAjaxOrAnyStaticOptions;
  var stripDiacritics = Select2.util.stripDiacritics;
  for(var z=0,len=fulloptions.length;z<len;z++){
    if(stripDiacritics(fulloptions[z].text.toUpperCase()).
        indexOf(stripDiacritics(opts.term.toUpperCase())) >= 0){
      res.push(fulloptions[z]);
    }
  }
  opts.callback({ results : res }); // res is your filtered/matching rows out of which first one will get auto hightlighted
}

      

0


source







All Articles