How to prevent the onSelect event from triggering twice in the DevBridge jQuery Autocomplete

A tipical issue that every developer of the DevBridge jQuery Autocomplete faces at the beginning of the development, is a very frustrating behaviour on the autocomplete when you click on the input that already has a selected option. Consider the following example:

var countries = [
    { value: 'Andorra', data: 'AD' },
    { value: 'Zimbabwe', data: 'ZZ' }
];

$('#autocomplete').autocomplete({
    lookup: countries,
    onSelect: function (suggestion) {
        alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
    }
});

Once the user selects an option, the onSelect callback will be triggered as expected. However, if the user clicks again in the input and there's already an option inside, the callback is triggered again, thing that obviously we don't want. For some reason this still happens even in the newer versions, because it seems there's people that need such behaviour. In my case, I don't need this, so a solution was necessary.

Solution

The solution is very simple though, because there's an option (not easy to find or understand in the docs) at least till de date, that prevents this behaviour from happening. This property is the triggerSelectOnValidInput, which in this case I want is as false:

triggerSelectOnValidInput: false

So you initialize the autocomplete with this option to prevent the issue:

var countries = [
    { value: 'Andorra', data: 'AD' },
    { value: 'Zimbabwe', data: 'ZZ' }
];

$('#autocomplete').autocomplete({
    lookup: countries,
    triggerSelectOnValidInput: false,
    onSelect: function (suggestion) {
        alert('You selected: ' + suggestion.value + ', ' + suggestion.data);
    }
});

Now the callback will be only triggered when the user searchs for something and selects something from the autocomplete dropdown.

Happy coding !

This could interest you

Become a more social person