html5 datalist to select only predefined options
Asked Answered
C

4

8

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?

Cingulum answered 28/5, 2015 at 6:53 Comment(0)
A
7

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>
Aconite answered 22/2, 2022 at 18:18 Comment(0)
P
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.

Psittacosis answered 28/5, 2015 at 7:1 Comment(2)
I was searching for something that can just filter selections from a predefined options list. Anyways, I switch to select box.Cingulum
When select element has too many entries to find by scrolling, datalist becomes better choice for this use case.Costate
V
1

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.

Viper answered 24/4, 2022 at 7:38 Comment(0)
N
0

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" />

Niddering answered 6/4, 2023 at 4:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.