Mohammad Adnan Mohammad Adnan - 10 months ago 83
Javascript Question

jQuery event for HTML5 datalist when item is selected or typed input match with item in the list

I have datalist like below -

<input id="name" list="allNames" />
<datalist id="allNames">
<option value="Adnan1"/>
<option value="Faizan2"/>

What I want is, when an item is typed in completely(for example say in input box when user completely type "Adnan1") or selected from list, then I want an event. I tried couple of approaches but both doesn't help me so far. Approaches are -


problem with this is, the event only gets triggered when input gets out of focus I.e. when I click somewhere in the screen.

I also tried

$("#name").bind('change', function () {

but the callback gets triggered each time when I type in. I actually need to make an AJAX call when item is completely selected. Either via type-in or by selecting from dropdown.

First approach is bad for user perspective because he has to make extra click and second has disadvantage as for every letter an event will be triggered.

All I want is an event when either user made a selection or typed complete sentence. is there a way to achieve this? any event that I missing and that can solve my problem.

Answer Source

On modern browsers, you can use input event, e.g:

$("#name").on('input', function () {
    var val = this.value;
        return this.value.toUpperCase() === val.toUpperCase();        
    }).length) {
        //send ajax request


PS: as input event has better support than datalist element, there is indeed no reason to not use it if you are already using datalist element.