Reputation: 53
I have this HTML with the following Input SearchBox and the Following Label that contains this Select Option.
I want to place the searchBox inside the Option so If I have 10000 This in that Select. To use the searchBox and select what option I want from there.
searchBox = document.querySelector("#searchBox");
countries = document.querySelector("#btd1");
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;
}
});
<!DOCTYPE html>
<html>
<head>
</head>
<body style="margin:0;">
<input id="searchBox" placeholder="Seach Project..." type="search">
<select id="btd1" name="Project">
<option disabled hidden="" selected value="">
Select Project *
</option>
</select>
</body>
</html>
The Option Box don't contain nothing cuz In my index it has a JS that Adds options with a add button.
Can anyone tell me please how can I make this work ?
Thanks a lot :)
Upvotes: 0
Views: 306
Reputation: 799
yeap, Here is your DEMO. What I have done is this; Get the value of the searchbox dynamicly onkeyup then count the number of options included. then get into a for loop to get the best macth and write it into the select. Of course then break when there is a match to prevent the loop go and check other matches and come with a result with less match but a match.
Upvotes: 1