I’m using the following (simplified) code. When the button is clicked, the input field gets focussed, however, the autocomplete list only shows, when I manually click in the input field…
const $input = document.getElementById('input');
const $button = document.getElementById('button');
$button.onclick = function() {
$input.focus();
//$input.click(); //doesn't work either
}
<input list="list" id="input">
<datalist id="list">
<option>List item</option>
</datalist>
<button id="button">show list</button>
2
Answers
The default visualization of the
<datalist>
element works only while you type in the input field. But you can provide your own visualization by changing the CSS style of the<datalist>
element. In the simplest variant, you simply change itsdisplay
attribute fromnone
toblock
:Does that help you?
To the best of my understanding, there is no truly native way to do this. There are hackie ways you can control this functionality (Which are usually horrible for ADA). But what you’d do is create a custom version of this, where you have full DOM control, and then trigger the open automatically.
There is a new method called
showPicker()
which does what you want, the only issue is that there’s limited support for it. Chrome 99+, Safari 16+, & Firefox 101+.My recommendation would be to use this inside a
try, catch
and then add helpful screen-reader descriptors.*Please note, that
showPicker()
doesn’t work here, but it does from a native script. There’s an error ofshowPicker() called from cross-origin iframe.
on Stackoverflows code thingy.