How can I make a browser display all datalist options when a default value is set?

Dave W picture Dave W · May 27, 2016 · Viewed 21.8k times · Source

I have an HTML form with a datalist and where the value is set with PHP, like

<input list="values" value="<?php echo $val; ?>">
 <datalist id="values">
  <option value="orange">
  <option value="banana">
 </datalist>

I want the user to see the options in the datalist, as well as the current value from the PHP. However, the "autocomplete" action causes values from the list that don't match (or start with) the current value to be hidden from the list, say if $val='apple'. Is there any way to avoid that, or is this behaviour fixed by the browser?

Answer

jakob picture jakob · May 27, 2016

<datalist> uses autocomplete functionality so this is normal behaviour.

For example if you set input value to be 'o' you will see just orange in datalist options. It checks word from first letter. But if you set input value to 'a' then you won't see options at all.

So if you already have value in input then nothing will be shown in datalist options except that value if it exists. It doesn't behave like select.

Workaround for this would be to use jquery like this for example:

$('input').on('click', function() {
  $(this).val('');
});
$('input').on('mouseleave', function() {
  if ($(this).val() == '') {
    $(this).val('apple');
  }
});

Full test here: https://jsfiddle.net/yw5wh4da/

Or you could use <select>. To me it is better solution in this case.