'html5 datalist to select only predefined options
I am using HTML5 datalist
to allow selection from a large list by autocomplete and filter feature. But I want to allow selection only from predefined options. See fiddle demo http://jsfiddle.net/tharas/rrkdu8pk/.
I want users to select only from values specified in <option>
tag. Is it possible?
Solution 1:[1]
If you don't want let the user type in anything by himself but select one of the options, you should better use a select
element instead of input
with datalist
. Otherwise you need to validate the content on change/submission.
Edit: You should also consider taking a look at datalists
(by now) poor browser coverage at caniuse.com.
Solution 2:[2]
You could use "onchange" on input to reset the value if not in options:
<body>
<!-- use 'required' for not letting the user submit the empty input
by hitting the enter button too quick-->
<input list="browsers" onchange="resetIfInvalid(this);" required >
<datalist id="browsers">
<option value="Edge">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
</body>
<script>
function resetIfInvalid(el){
//just for beeing sure that nothing is done if no value selected
if (el.value == "")
return;
var options = el.list.options;
for (var i = 0; i< options.length; i++) {
if (el.value == options[i].value)
//option matches: work is done
return;
}
//no match was found: reset the value
el.value = "";
}
</script>
Solution 3:[3]
If you want to offer default values from the datalist only but accept new inputs (a bit like what a typeahead input does) you can add autocomplete="off"
<input list="theaters" name="theaters" autocomplete="off">
<datalist id="theaters">
<option value="rice">
...
</datalist>
if by only you mean exclusively then as mentioned before, select
is the right choice.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | naeramarth7 |
Solution 2 | Lukas |
Solution 3 | MoVod |