I have this example:
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Google Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
I need to catch an event, when the user selects option (with mouse or keyboard).
I tried to do onchange="MySuperFunction();"
, but this works only when an item is selected and then the list is unfocused.
The input
event should work for what you need. As I understand, you can't use a datalist directly, but it is connected to an input by the list
attribute. This event binding would go on that input:
document.getElementById('browsers-input').addEventListener('input', function () {
console.log('changed');
});
To get the same effect of "Explosion Pills" solution using JQuery style:
$("#browsers-input").on("input", MySuperFunction);
Usin jQuery
you could use .change
http://jquery.com/
$('datalist#browsers').change(MySuperFunction);
or
$('datalist#browsers').change(function(){
// stuff
});
来源:https://stackoverflow.com/questions/15147728/input-list-selection-changed-event