Home > OS >  how to get value of selected datalist
how to get value of selected datalist

Time:12-20

how do get value of datalist by selection of country. can i get value by onchange?

function fun(el) {
  var x = document.getElementById('countrydata').value;
  alert(x)
}
<datalist id="countrydata" onchange="fun(this);">
  <option value="Afghanistan">Afghanistan</option>
  <option value="Åland Islands">Åland Islands</option>
  <option value="Albania">Albania</option>
  <option value="India">India</option>
</datalist>
<label for="country">country</label>
<input type="text" list="countrydata" id="country" name="country" size="50" autocomplete="off" />

CodePudding user response:

Move the onchange="fun(this);" from datalist to input.

<datalist id="countrydata">
     <option value="Afghanistan">Afghanistan</option>
     <option value="Åland Islands">Åland Islands</option>
     <option value="Albania">Albania</option>
     <option value="India">India</option>
   </datalist>
<label for="country">country</label>
<input type="text"
  list="countrydata"
  id="country" name="country"
  size="50"
  autocomplete="off"
 onchange="fun(this);" />
<script>
    function fun(el){
        var x = document.getElementById('country').value;
        alert(x)
    }
 </script>
  • Related