5120bee 5120bee - 7 days ago 5
HTML Question

Is there a potential way to disable user input in a <datalist>?

I'm debating between using a

<select>
or
<datalist>
to display a drop-down list from which the user can select the items.

One downside of the
<select>
tag is that it's inconsistent as it renders differently in different browsers: some browsers it displays with scroll bar, and for some it's a drop-down list.

The
<datalist>
on the other hand seems good but I just want to know if there is any way to disable the text input where the user can type whatever they want in the text box if they don't click the down arrow button on the input field as shown:



​<form action="demo_form.asp" method="get">
<input list="browsers" name="browser">
<datalist id="browsers">
<option value="Internet Explorer">
<option value="Firefox">
<option value="Chrome">
<option value="Opera">
<option value="Safari">
</datalist>
<input type="submit">
</form>





Is there someway to disable the input bar while keeping the dropdown list? I tried the 'readonly' attribute but that renders the whole non-clickable.

Answer

You could use the pattern attribute on the input element to restrict the allowed values:

​<form action="demo_form.asp" method="get">
  <input list="browsers" name="browser"
    pattern="Internet Explorer|Firefox|Chrome|Opera|Safari"
    title='Must be "Internet Explorer", "Firefox", "Chrome", "Opera", or "Safari"'>
  <datalist id="browsers">
    <option value="Internet Explorer">
    <option value="Firefox">
    <option value="Chrome">
    <option value="Opera">
    <option value="Safari">
  </datalist>
  <input type="submit">
</form>
Comments