Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fire an event on clicking data list option list?

I have a datalist that looks like :

<datalist id="foodlist">
	
		<option value="one" ></option
		<option value="two" ></option>
		<option value="three" ></option>
	
</datalist>

<input type="text" list="foodlist" autocomplete=true id="inputItem"/>

I want an event to fire when user selects on of the option in the list using JavaScript.

How to achieve it?

onClick, onChange does not seem to work.

like image 524
RosAng Avatar asked Dec 25 '22 16:12

RosAng


1 Answers

I know this is kind of old, but I thought I should document it somewhere. If you're trying to detect input from a dropdown selection rather than a click per se, you can use the "input" event and check the type of the passed event object - cut/paste/keypress input will pass an "InputEvent" object, whereas a datalist selection will pass a generic "Event" object.

var textbox = document.getElementById("inputItem");
textbox.addEventListener("input", function(e){
    
    var isInputEvent = (Object.prototype.toString.call(e).indexOf("InputEvent") > -1);
    
    if(!isInputEvent)
        alert("Selected: " + e.target.value);
    }, false);
<datalist id="foodlist">
	
		<option value="one" ></option>
		<option value="two" ></option>
		<option value="three" ></option>
	
</datalist>

<input type="text" list="foodlist" autocomplete=true id="inputItem"/>
like image 155
Couchy X Avatar answered Jan 06 '23 03:01

Couchy X