I have datalist like below -
Check if this works for you :
var dataList=[];
$("#allNames").find("option").each(function(){dataList.push($(this).val())})
console.log(dataList);
$("#name").on("keyup focus blur change",function(){
if(dataList.indexOf($(this).val())!=-1)
console.log("change");
})
I pushed datalist options into array , and on change event keyup , blur or focus , i check if input value exists in my datalist array.
Simple solution
document.getElementById('name').addEventListener('input', function () {
console.log('changed');
});
Hacky as a sin, but works for me. (Note that if you are typing 'Rum-Cola' it doesn't stop on the 'Rum' option)
const opts = $("option").map(function(){return this.value;}).get();
$("#favourite-drink").on("keydown", function(e){
if(e.key){ // in case of mouse event e.key is 'undefined'
if (e.key === "Enter") { // looks like user wants to confirm the choice
if(opts.indexOf(this.value) >= 0){
this.blur();
console.log("Selected: " + this.value);
}
}
else {
this.setAttribute("data-keyboardinput", "true"); // remember that it's keyboard event
setTimeout(function(){ //and keep it in memory for 100ms
this.removeAttribute("data-keyboardinput")
}.bind(this), 100);
}
}
});
$("#favourite-drink").on("input", function(){
if(!this.dataset.keyboardinput && opts.indexOf(this.value) >= 0){ // if it's not a key press followed event
console.log("Selected: " + this.value);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Choose a drink:</p>
<input id="favourite-drink" list="drinks">
<datalist id="drinks">
<option value="Rum"></option>
<option value="Rum-Cola"></option>
<option value="Vodka"></option>
</datalist>
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.
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>