I am using a datalist and need to detect when the user selects something from the drop-down list. A similar question has been asked BUT I need it so that the event fires ONLY when the user selects something from the datalist. If they type something in the input then I do NOT want the event to fire. (Notice in the accepted answer to the question I linked that they bind the input, which is not what I want). I've tried (with no success):
<datalist>
<option>Option 1 Here</option>
<option>Option 2 Here</option>
</datalist>
$(document).on('change', 'datalist', function(){
alert('hi');
});
EDIT: This question is different than the suggested question because it's a completely different question.
Replace the datalist by select tag. Or if you want to use <datalist> you can use event onchange on the <input> tag and check if the value of your input is into the values of datalist.
Like select elements, the datalist element has very little flexibility in styling. You cannot style any of the suggested terms if that's what your question was asking. Browsers define their own styles for these elements.
Generally, both the tags are used for choosing an option from the given list. But the main difference between both is that in the <datalist> tag the user can enter its own input and add that as an option with the help of the <input> element whereas the <select> tag doesn't provide this feature.
The <datalist> tag is used to provide an "autocomplete" feature for <input> elements. Users will see a drop-down list of pre-defined options as they input data.
You can manually check it on change. But you need to check change of the input of datalist.
$(document).on('change', 'input', function(){
var options = $('datalist')[0].options;
var val = $(this).val();
for (var i=0;i<options.length;i++){
if (options[i].value === val) {
alert(val);
break;
}
}
});
FIDDLE
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With