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 onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed. Tip: This event is similar to the oninput event.
The oninput event occurs when an element gets user input. This event occurs when the value of an <input> or <textarea> element is changed.
Definition and UsageThe oninput attribute fires when the value of an <input> or <textarea> element is changed. Tip: This event is similar to the onchange event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.
Using JavaScript change event for radio buttons First, register an event handler to the change event of the body . When a radio button is clicked, its change event is bubbled to the body. This technique is called event delegation. Then, show a corresponding message based on which radio button is selected.
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 (event) {
if (event.inputType == 'insertReplacementText')
console.log('autocomplete option selected');
});
http://jsfiddle.net/vccfv/
To get the same effect of "Explosion Pills" solution using JQuery style:
$("#browsers-input").on("input", MySuperFunction);
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