'Filter in Javascript
My goal is to be able to filter list and show all the items in that group only (e.g all list items in Cakes)... So far, what I've created is that, once searched, it will only shows exact matches. Is there a way I can show the complete list group (e.g all list items in Cakes)?
Also, can someone help me understand why the filter only runs on parent lists? I mean, I tried searching "water" but it does not show anything. My understanding of the code is that it goes through all the list and shows the matches, but I dont know why when the input is not found in the parent list, it does not proceed to the sublist? not sure if that is the behavior.
If you can share some suggestions, or an ideas I can use as a guide, that would be a very big help. Thank you! :)
var input2 = document.getElementById('myInput');
var toggler = document.getElementsByClassName("caret");
input2.onkeyup = function(event) {
var input, filter, ul, li, a, i, y, txtValue;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
ul = document.getElementById("main");
li = ul.getElementsByTagName("li");
for (i = 0; i < li.length; i++) {
a = li[i].getElementsByTagName("a")[0];
txtValue = a.textContent || a.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) {
li[i].style.display = "";
} else {
li[i].style.display = "none";
}
}
}
<div>
<input type="text" id="myInput" />
<ul id="main">
<li class="item">
<span class="caret"><a href="#">/Beverages</a></span>
<ul class="nested">
<li class="item">
<a href="/#">/Water</a> </li>
<li class="item">
<a href="#">/Coffee</a> </li>
<li class="item">
<a href="#">/Tea</a> </li>
<li class="item">
<span class="caret">
<a href="#">/Beverages/Tea/Warm</a> </span>
<ul class="nested">
<li class="item">
<a href="#">/Black Tea</a> </li>
<li class="item">
<a href="#">/White Tea</a> </li>
<li class="item">
<a href="#">/Red Tea</a> </li>
</ul>
</li>
</ul>
</li>
<li class="item">
<span class="caret"><a href="/about-us/annual-report">/Cakes/Cheesecake</a></span>
<ul class="nested">
<li class="item">
<a href="#">/Strawberry</a> </li>
<li class="item">
<a href="#">/Blueberry</a> </li>
<li class="item">
<a href="#">/Caramel</a></li>
<li class="item">
<span class="caret">
<a href="#">/Cakes/Cheesecake/Size</a> </span>
<ul class="nested">
<li class="item">
<a href="#">/Whole</a> </li>
<li class="item">
<a href="#t">/Half</a> </li>
</ul>
</li>
</ul>
</li>
</UL>
</li>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|