Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select2 type to select

I'm trying to use select2 to have a multi-select dropdown list of states, but something is wrong.

Normally, when you type an option out, it's highlighted so that you can hit enter and select it. It underlines the option, but does not highlight it, so if I type "alabama" but hit enter, it will select "arkansas".

I'm 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 sort of parameter? I could have sworn this was working fine the last time I used it. No console errors, and it click selects perfectly.

Note that the github page works just like I want (when you type, it selects the first option that matches) enter image description here

like image 390
Sterling Archer Avatar asked Jul 03 '26 23:07

Sterling Archer


1 Answers

In Select2 3.x, the highlighted result in the dropdown will always be the first result during searches. This will be changing in Select2 4.x, so the selected option will be selected if it is present.

You are looking for the results to be sorted differently. By default, Select2 orders options by the order that they have within the DOM, not by how relevant they are. The documentation provides an example of how to customize the sorting of results using the sortResults option.

Keep in mind that it is more efficient to sort the results on the server side when using AJAX, which is why Select2 does not do any further sorting. This would explain why "Arkansas" is being returned when searching for "Alabama".

like image 90
Kevin Brown-Silva Avatar answered Jul 05 '26 15:07

Kevin Brown-Silva



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!