How to show datalist suggestions using javascript?

空扰寡人 提交于 2019-11-29 08:09:17

问题


I find the new <datalist> generally very useful, but I think that the suggestions are not visible enough. Is there a way to trigger the display of datalist suggestions using javascript?

As an example, I have a datalist on an <input type="number"> (jsFiddle).

<label>
    Enter a Fibonacci number:
    <input type="number" list="fibonacci" min="0" id="myinput">
</label>
<datalist id="fibonacci">
    <option value="0">
    <option value="1">
    <option value="2">
    <option value="3">
    <option value="5">
    <option value="8">
    <option value="13">
    <option value="21">
</datalist>
<button type="button" id="show-suggestions">Show suggestions</button>

<script>
$('#show-suggestions').click(function() {
    // .showSuggestions() does not exist.
    // I'd like it to display the suggested values for the input field.
    $('#myinput').showSuggestions();
});
</script>

In Chrome, the full list of suggestions is shown only when the input is empty, already has focus, and the user then clicks on the input. The down arrow does not show the suggestions - it simply decrements the value.

I'd like to make the suggestions more visible. As an example I've added a button that's supposed to open the list of suggestions. What do I put in the onClick-handler?

I've used Chrome, jQuery and a number-input in this example, but I'd prefer a generic solution independent of all of those.


回答1:


If you remove the type="number" your users can get the dropdownlist using the basic alt+downarrow keyboard shortcut.

If that doesn't work for you. I suggest using a hybrid approach such as https://github.com/mmurph211/Autocomplete



来源:https://stackoverflow.com/questions/14381217/how-to-show-datalist-suggestions-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!