I have the following question, I have a select with several elements and a filter function. That works fine for me, but I would like to know if there is a way to dynamically adjust the size of the select based on matches. I can't think of any other way than the silver one.
Thank you very much!!
<div>
<div>
<input type="text" id="search" name="search" style="margin: 10px;width: 165px;" onkeyup="filter()">
</div>
<div>
<select id="select" size="20">
<option>Cupcake</option>
<option>Cunut</option>
<option>Eclair</option>
<option>Froyo</option>
<option>Gingerbread</option>
<option>Honeycomb</option>
<option>Ice Cream Sandwich</option>
<option>Jelly Bean</option>
<option>Kitkat</option>
<option>Lollipop</option>
<option>Marshmallow</option>
<option>Nougat</option>
</select>
</div>
</div>
<script>
function filter(){
var keyword = document.getElementById("search").value;
var select = document.getElementById("select");
for (var i = 0; i < select.length; i++) {
var txt = select.options[i].text;
txt = txt.toLowerCase();
if (!txt.match(keyword)) {
select.options[i].setAttribute('disabled', 'disabled');
select.options[i].setAttribute("hidden", "hidden");
select.size = "4";
} else {
select.options[i].removeAttribute('disabled');
select.options[i].removeAttribute("hidden");
select.size = "1";
}
}
}
</script>
Hope this answers your question (explanations below):
Explanation of the changes
I have created a new one
<div>
with the id errMsg in the HTML to reserve a space to put an error message in case there are no matches.I have converted both the keyword variable and the txt variable to lowercase with toLowerCase() for later comparison (in your case you forgot to do it in the keyword ).
I have initialized a new variable named matches which will hold the total of matches found, before the loop.
I changed
select.length
toselect.options.length
basically because it didn't work well for me, hehI have changed the match() method to the includes() method because match() is oriented to regular expressions, and here it was not necessary.
In each match found I have added 1 to the matches variable