Get selected value of datalist option value using javascript
17,408
Solution 1
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);
}
Solution 2
You can check the trimmed value of the input. If value is not empty then you can get the selected data list option by matching the value attribute with querySelector()
.
Try the following way:
function AddValue(el, dl){
if(el.value.trim() != ''){
var opSelected = dl.querySelector(`[value="${el.value}"]`);
var option = document.createElement("option");
option.value = opSelected.value;
option.text = opSelected.getAttribute('label');
document.getElementById('Colors').appendChild(option);
}
}
<input id="SelectColor" type="text" list="AllColors">
<datalist id="AllColors">
<option label="Red" value="1"></option>
<option label="Yellow" value="2"></option>
<option label="Green" value="3"></option>
<option label="Blue" value="4"></option>
</datalist>
<button type="button" onclick="AddValue(document.getElementById('SelectColor'), document.getElementById('AllColors'));">Add</button>
<select id="Colors" size="3" multiple></select>
![Alberto Muñoz Sánchez](https://lh3.googleusercontent.com/-ngnguIlmiRQ/AAAAAAAAAAI/AAAAAAAAARY/pmx7P2s7_2Y/photo.jpg?sz=256)
Author by
Alberto Muñoz Sánchez
Updated on June 24, 2022Comments
-
Alberto Muñoz Sánchez about 2 years
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); }