Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 571
Mohammad Adnan Avatar asked May 10 '15 12:05

Mohammad Adnan


2 Answers

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

$("#name").on('input', function () {      var val = this.value;      if($('#allNames option').filter(function(){          return this.value.toUpperCase() === val.toUpperCase();              }).length) {          //send ajax request          alert(this.value);      }  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>    <input id="name" list="allNames" />  <datalist id="allNames">      <option value="Adnan1" />      <option value="Faizan2" />  </datalist>

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.

like image 128
A. Wolff Avatar answered Oct 12 '22 10:10

A. Wolff


You can use input event for achieving such functionality, as below :

$(document).ready(function() {    $('#name').on('input', function() {      var userText = $(this).val();        $("#allNames").find("option").each(function() {        if ($(this).val() == userText) {          alert("Make Ajax call here.");        }      })    })  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <input id="name" list="allNames" />  <datalist id="allNames">    <option value="Adnan1" />    <option value="Faizan2" />  </datalist>
like image 40
Ankit Avatar answered Oct 12 '22 10:10

Ankit