How to show datalist suggestions using JavaScript?
Asked Answered
S

2

13

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.

Snippet answered 17/1, 2013 at 14:26 Comment(0)
O
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

Ovary answered 6/2, 2013 at 11:1 Comment(0)
C
-1

Picking your country from a list containing more than 200 options is an ideal candidate for an autocomplete control. Define a <datalist> with child <option> elements for every country directly in an HTML page:

 <datalist id="countrydata">
       <option>Afghanistan</option>
       <option>Åland Islands</option>
       <option>Albania</option>
       <option>Algeria</option>
       <option>American Samoa</option>
       <option>Andorra</option>
       <option>Angola</option>
       <option>Anguilla</option>
       <option>Antarctica</option>
       ...etc...
    </datalist>
Carmelocarmen answered 16/12, 2021 at 15:21 Comment(1)
You can improve your questions by reading this article.Crispy

© 2022 - 2024 — McMap. All rights reserved.