Sometimes, we want to show datalist labels but submit the actual value with JavaScript.
In this article, we’ll look at how to show datalist labels but submit the actual value with JavaScript.
How to show datalist labels but submit the actual value with JavaScript?
To show datalist labels but submit the actual value with JavaScript, we can store the value we submit in a data attribute.
For instance, we write
<input list="answers" id="answer" />
<datalist id="answers">
<option data-value="42" value="The answer"></option>
</datalist>
to add an input with its datalist element.
Then we write
const shownVal = document.getElementById("answer").value;
const value2send = document.querySelector(
`#answers option[value='"${shownVal}"']`
).dataset.value;
to get the value of the input with document.getElementById("answer").value
.
Then we get the option with the value with document.querySelector(
#answers option[value=’"${shownVal}"’]);
.
And then we get its data-value
attribute with the dataset.value
property.
Conclusion
To show datalist labels but submit the actual value with JavaScript, we can store the value we submit in a data attribute.