Mohammad Adnan Mohammad Adnan - 1 month ago 19
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"/>
</datalist>


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 -

$("#name").change(function(){
console.log("change");
}


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 () {
console.log('changed');
});


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

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

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

-DEMO-

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.