Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perform action when clicking HTML5 datalist option

I'm using a <datalist>

<datalist id="items"></datalist> 

And using AJAX to populate the list

 function callServer (input) {     xmlhttp = new XMLHttpRequest();     xmlhttp.onreadystatechange = function(){         if (xmlhttp.readyState == 4 && xmlhttp.status == 200){             //return the JSON object             console.log(xmlhttp.responseText);             var arr = JSON.parse(xmlhttp.responseText);             var parentDiv = document.getElementById('items');             parentDiv.innerHTML = "";             //fill the options in the document             for(var x = 0; x < arr.length; x++) {                 var option = document.createElement('option');                 option.value = arr[x][0];                 option.innerHTML = arr[x][1];                 //add each autocomplete option to the 'list'                 option.addEventListener("click", function() {                   console.log("Test");                 });                 parentDiv.appendChild(option);             };          }     }     xmlhttp.open("GET", "incl/search.php?value="+input.value, true);     xmlhttp.send(); } 

However I can't get it to perform an action when I click on a selection in the datalist, for example if I type in "Ref F" and the item "Ref flowers" comes up, if I click on it I need to execute an event.

How can I do this?

option.addEventListener("click", function() { option.addEventListener("onclick", function() { option.addEventListener("change", function() { 
like image 583
Hobbyist Avatar asked May 04 '15 04:05

Hobbyist


People also ask

What does Datalist do in HTML?

Definition and Usage 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.

Is there a way to apply a CSS style on HTML5 Datalist options?

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.

Which attribute of input element can be used with Datalist element of HTML5?

The list attribute of the input element is used to bind it together with a datalist element.


2 Answers

Sorry for digging up this question, but I've had a similar problem and have a solution, that should work for you, too.

function onInput() {      var val = document.getElementById("input").value;      var opts = document.getElementById('dlist').childNodes;      for (var i = 0; i < opts.length; i++) {        if (opts[i].value === val) {          // An item was selected from the list!          // yourCallbackHere()          alert(opts[i].value);          break;        }      }    }
<input type='text' oninput='onInput()' id='input' list='dlist' />    <datalist id='dlist'>    <option value='Value1'>Text1</option>    <option value='Value2'>Text2</option>  </datalist>

This solution is derived from Stephan Mullers solution. It should work with a dynamically populated datalist as well.

Unfortunaltely there is no way to tell whether the user clicked on an item from the datalist or selected it by pressing the tab-key or typed the whole string by hand.

like image 129
chillichief Avatar answered Sep 22 '22 06:09

chillichief


Due to the lack of events available for <datalist> elements, there is no way to a selection from the suggestions other than watching the input's events (change, input, etc). Also see my answer here: Determine if an element was selected from HTML 5 datalist by pressing enter key

To check if a selection was picked from the list, you should compare each change to the available options. This means the event will also fire when a user enters an exact value manually, there is no way to stop this.

document.querySelector('input[list="items"]').addEventListener('input', onInput);    function onInput(e) {     var input = e.target,         val = input.value;         list = input.getAttribute('list'),         options = document.getElementById(list).childNodes;      for(var i = 0; i < options.length; i++) {      if(options[i].innerText === val) {        // An item was selected from the list!        // yourCallbackHere()        alert('item selected: ' + val);        break;      }    }  }
<input list="items" type="text" />  <datalist id="items">    <option>item 1</option>    <option>item 2</option>  </datalist>
like image 34
Stephan Muller Avatar answered Sep 25 '22 06:09

Stephan Muller