Is there a SelectedIndex for an HTML5 DataList?

Caio picture Caio · Jan 18, 2011 · Viewed 21.6k times · Source

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>

Answer

David Tang picture David Tang · Jan 18, 2011

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);