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?
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>
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.
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.
it's possible
if you avoid special input-names like: email, name, city...
depends on how you choose your input name
instead of <input type="text" name="email" autocomplete="off" />
use: <input type="text" name="email_" autocomplete="off" />
© 2022 - 2024 — McMap. All rights reserved.