Answer
Yes, you can, firstly, see it in action in this demo , if you like what you see, here's how to do it:
HTML
<input type="search" id="searchBox"> <select id="countries"> <option value="arg">Argentina</option> <option value="usa">United States of America</option> <option value="som">Somalia</option> </select>
This is pretty straight forward, search input and selection with several options.
Javascript
searchBox = document.querySelector("#searchBox"); countries = document.querySelector("#countries"); var when = "keyup"; //You can change this to keydown, keypress or change searchBox.addEventListener("keyup", function (e) { var text = e.target.value; var options = countries.options; for (var i = 0; i < options.length; i++) { var option = options[i]; var optionText = option.text; var lowerOptionText = optionText.toLowerCase(); var lowerText = text.toLowerCase(); var regex = new RegExp("^" + text, "i"); var match = optionText.match(regex); var contains = lowerOptionText.indexOf(lowerText) != -1; if (match || contains) { option.selected = true; return; } searchBox.selectedIndex = 0; } });
Explanation
Variables first:
- searchBox : link to the
HTMLElement tab. - countries : select the
HTMLElement link. - when : the type of event, I used "keyup", and this means that the selection will be updated when you click and raise the key in the SearchBox.
- text, lowerText : value of searchBox (in other words, input text). The second is the first, but the bottom is for checking case sensitivity.
- parameters . Object selection options.
- optionText, lowerOptionText : the text of the
object option (ej. "Argentina"), and the other is the lower version for checking case sensitivity (ej. "argentina") - regex . This is a
RegExp Object , a regular expression, basically what it does is testing (case insensitive, due to the "i" in the second parameter) so that the line starts with some value, in this case it will be the input text. - match : it executes the
RegExp Object again the option text, this means that it will check whether the entered text is the same as the beginning of the option text. - contains : it checks if the option text contains the entered text.
Few, it was a lot, so why do we need 2 tests? Since there are two choices with searchBox, one of them is that when you start typing “Unit ..”, it should match “United States of America” (regexp), and the other just enter “America.” and it should also comply with the "United States of America" (contains)
So, he checks both tests, and if one of them is correct, he will choose this option. (He will also return so that he will not continue executing the code)
By default, if no test is true, it will select the first selection item.
Hope that helps :)
source share