Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
939 views
in Technique[技术] by (71.8m points)

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...