skip to Main Content

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


  1. 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 its display attribute from none to block:

    document.querySelector("datalist").addEventListener("click", function(event) {
      if (event.target.nodeName === "OPTION")
        document.querySelector("input").value = event.target.textContent;
    }, true);
    datalist.preview {
      display: block;
    }
    
    input:focus~datalist {
      display: none;
    }
    <input list="list" id="input">
    <button onclick="document.querySelector('datalist').classList.add('preview')">show list</button>
    <datalist id="list">
      <option>List item</option>
    </datalist>

    Does that help you?

    Login or Signup to reply.
  2. 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 of showPicker() called from cross-origin iframe. on Stackoverflows code thingy.

    1. Show a browser picker
    2. MDN showPicker()
    3. showPicker() support
    const $input = document.getElementById('input');
    const $button = document.getElementById('button');
    
    $button.onclick = function() {
      $input.focus();
      //$input.click(); //doesn't work either
      try {
        $input.showPicker();
      } catch (error) {
        console.error(error);
      }
    }
    <input list="list" id="input">
    <datalist id="list">
      <option>List item</option>
     </datalist>
    <button id="button">show list</button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search