How to show datalist suggestions using javascript?

2019-02-04 18:30发布

问题:

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