Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input List Selection Changed Event

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.

like image 867
swamprunner7 Avatar asked Feb 28 '13 23:02

swamprunner7


People also ask

What is Onchange event?

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.

Which input event will you use on an input tag to get notified every time a user changes something?

The oninput event occurs when an element gets user input. This event occurs when the value of an <input> or <textarea> element is changed.

What is Oninput?

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.

How do you change an event in JavaScript?

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.


2 Answers

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/

like image 178
Explosion Pills Avatar answered Sep 22 '22 08:09

Explosion Pills


To get the same effect of "Explosion Pills" solution using JQuery style:

$("#browsers-input").on("input", MySuperFunction);
like image 38
Olivier Royo Avatar answered Sep 20 '22 08:09

Olivier Royo