Home > Net >  How to get text on datalist option with pure javascript
How to get text on datalist option with pure javascript

Time:07-20

i have datalist option and i want to get the text value and not the value, the picture below is the example, i want to get the Kuruha as the text and not the 1 value, how to get it properly ?

html code :

        <datalist id="in">
        <option value="1">Kuruha</option>
        <option value="2">Agencia</option>
        </datalist>
        <input list="in" id=int>

picture example

enter image description here

CodePudding user response:

You can bind the change eventListener as usual on your input element, and then access its datalist.

Once there, you can filter it with find to extract the selected option (if any), and finally get the text tusing textContent.

document.getElementById('int').addEventListener('change', function() {
  let selectedOpt = Array.from(this.list.options).find(item => item.value == this.value);
  
  if (typeof selectedOpt == 'undefined') {
    document.getElementById('results').innerHTML = '';
  } else {
    document.getElementById('results').innerHTML = selectedOpt.textContent;
  }
});
<datalist id="in">
   <option value="1">Kuruha</option>
   <option value="2">Agencia</option>
 </datalist>
<input list="in" id="int">

<div id="results"></div>

  • Related