javascriptinputautosuggestoptionmenuhtml-datalist

How can I get the suggested values from an input datalist using pure Javascript?


I'm using a plain text input plus datalist to suggest values as the user interacts with the input. I'd like to know if there's a way to get the suggested items shown.

E.g.

    document.getElementById('myBrowser').addEventListener('input', function() {
      console.log(this.list.suggested); // logs out the suggested values 
    });
    <label for="myBrowser">Choose a browser from this list:</label>
    <input list="browsers" id="myBrowser" name="myBrowser" />
    <datalist id="browsers">
      <option value="Chrome"></option>
      <option value="Firefox"></option>
      <option value="Opera"></option>
      <option value="Safari"></option>
      <option value="Microsoft Edge"></option>
    </datalist>

So if I type 'Fire' the suggestion values should just be ['Firefox']


Solution

  • You can do something like this :

    // Obtain the available browsers
    let options = Array.from(document.querySelectorAll('#browsers option')).map((option) => option.value);
    
    document.getElementById('myBrowser').addEventListener('input', function () {
      const hint = this.value.toLowerCase();
      // Obtain options matching input
      const suggestions = options.filter((option) => option.toLowerCase().includes(hint));
    
      console.log(suggestions);
    });
    <label for="myBrowser">Choose a browser from this list:</label>
    <input list="browsers" id="myBrowser" name="myBrowser" />
    <datalist id="browsers">
      <option value="Chrome"></option>
      <option value="Firefox"></option>
      <option value="Opera"></option>
      <option value="Safari"></option>
      <option value="Microsoft Edge"></option>
    </datalist>

    This obtains the exact same list as on Chrome, but that may not be the case on other browsers.

    As for directly accessing the proposed list from the browser, I cannot say for sure if that is doable.