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’]
2
Answers
You can do something like this :
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.
One could implement such an additional
suggestedValue
property as getter of theHTMLInputElement.prototype
.The suggested solution has to be implemented as direct property of an input-element and not like the OP suggested … "
[inputElement].list.suggested
" … as property of a datalist-element … since<datalist/>
, via itsid
-attribute, can be referred to by more than just one element, each via itslist
-attribute.Thus, a possible implementation and usage could look like follows …