javascripthtmlhtml-datalist

Get selected value of datalist option value using javascript


I need to add some values from a HTML5 DataList to a <select multiple> control just with Javascript. But I can't guess how to do it.

This is what I have tried:

<input id="SelectColor" type="text" list="AllColors">
<datalist id="AllColors">
  <option label="Red" value="1">
  <option label="Yellow" value="2">
  <option label="Green" value="3">
  <option label="Blue" value="4">
</datalist>

<button type="button" onclick="AddValue(document.getElementById('AllColors').value, document.getElementById('AllColors').text);">Add</button>
<select id="Colors" size="3" multiple></select>
function AddValue(Value, Text){

//Value and Text are empty!

var option=document.createElement("option");
option.value=Value;
option.text=Text;

document.getElementById('Colors').appendChild(option);

}

Solution

  • This should work. I have moved the value selection logic into the method itself. You will only get the value from the input. You will need to use the value to select the label from the datalist.

    function AddValue(){
      const Value = document.querySelector('#SelectColor').value;
    
      if(!Value) return;
    
      const Text = document.querySelector('option[value="' + Value + '"]').label;
    
      const option=document.createElement("option");
      option.value=Value;
      option.text=Text;
    
      document.getElementById('Colors').appendChild(option);
    }
    

    Here is the working demo.