I have defined a searchable select list, as defined below. What I would like is to get the data-value field once a selection is made, while the user will still see the option value string. This field will contain the internal id of the entry.
If I define this id, as a value attribute, the dropdown list will show both the id and the string , and after selection only the id will be visible in the input field.
I’ve found some posts taking about using data-* attributes to work around this problem, but for some reasons, I’m not able to get this value from the input field, after the selection was completed.
Any idea how I can achieve this?
Thanks
PS: I’m only interested in pure JavaScript solutions.
<html>
<head>
<script>
function onchangeTest(){
alert(document.getElementById("input").value);
}
</script>
</head>
<body>
<div id="share">
<input type="text" id="input" list="datalist" onchange="onchangeTest()">
<datalist id="datalist">
<option data-value="1">Foo</option>
<option data-value="2">Bar</option>
<option data-value="3">Baz</option>
<option data-value="4">Foo Bar</option>
<option data-value="5">Bar Baz</option>
</datalist>
</div>
</body>
</html>
3
Answers
For whoever will be interested in the future, I've ended up dropping the input datalist approach and picked this search dropdown list implementation instead:
https://github.com/Godsont/Custom-Select-Box-with-Search
You can check all the options to find the option with a matching value (if any), then read from its
dataset
.In the event handler function, you can loop through the options in the datalist, compare the input value with the option’s text content, and retrieve the data-value attribute when there’s a match:
I see two problems with this approach
options.textContent
should be unique to always work expectedonchange
this might slow down your frontend performance with a large list. If this problem occurs I recommend you to use the debounce technique to prevent excessive function calls while typing.