You can pick the current option
of any select
element:
mySelect.options[mySelect.selectedIndex]
Can I do the same with a DataList? Something like this:
<input id = "input" list = "datalist" type = "text" />
<datalist id = "datalist">
<option value = "No. 1"></option>
<option value = "No. 2"></option>
<option value = "No. 3"></option>
</datalist>
<script>
var datalist = document.getElementById ("datalist");
var input = document.getElementById ("input");
input.addEventListener ("keyup", function (event) {
if (event.which === 13) {
alert (datalist.options[datalist.selectedIndex]); // Example
}
}, false);
</script>
Lets say you have data attributes in the above example like this,
<input list="browsers" name="browser" value="Internet Explorer">
<datalist id="browsers">
<option value="Internet Explorer" data-company="Microsoft">
<option value="Firefox" data-company="Mozilla">
<option value="Chrome" data-company="Google/Alphabet">
<option value="Opera" data-company="Opera">
<option value="Safari" data-company="Apple">
</datalist>
and you want to obtain the data-company attribute of the selected item,
using the loop above
for (var i=0;i<datalist_id.options.length;i++) {
if (datalist_id.options[i].value == input_id.value) {
// obtains the data-company attrbute
console.log(datalist_id.options[i].getAttribute("data-company");
alert(datalist_id.options[i].innerText);
break;
}
}
No, the datalist element is for providing autocomplete to inputs. It is a source of data, is hidden from the user, and multiple inputs may link to it. Therefore it doesn't make sense to have a selectedIndex
.
Instead, you should simply check the .value
of the input:
var datalist = document.getElementById ("datalist");
var input = document.getElementById ("input");
input.addEventListener ("keyup", function (event) {
if (event.which === 13) {
alert(input.value);
}
}, false);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With