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?
<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.