Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this javascript code that is supposed to only show results that match typed input filter only the first 10 options?

I have a piece of code (only a snippet, everything else is css) that as I type shows only the options that match my typed input. But for some reason, it only filters the first 10 options. The rest of the options just show no matter what. Any ideas why?

function myFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("mySearch");
  filter = input.value.toUpperCase();
  ul = document.getElementById("myMenu");
  li = ul.getElementsByTagName("li");
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}
a { color: white }
<div class="row">
  <div class="left" style="background-color:#2D2D2D; color: white;">
    <h2>***PAVADINIMAS***</h2>
    <input type="text" id="mySearch" onkeyup="myFunction()" placeholder="Paieška" title="Type in a category">
    <ul id="myMenu">
      <li><a href="#">Option1</a></li>
      <li><a href="#">Test</a></li>
      <li><a href="#">Lorem ipsum</a></li>
      <li><a href="#">abcde</a></li>
      <li><a href="#">monday</a></li>
      <li><a href="#">tuesday</a></li>
      <li><a href="#">wednesday</a></li>
      <li><a href="#">thrusday</a></li>
      <li><a href="#">friday</a></li>
      <li><a href="#">saturday</a>
      <li>
      <li><a href="#">sunday</a></li>
      <li><a href="#">test2</a></li>
      <li><a href="#">iii</a></li>
      <li><a href="#">12345</a></li>
      <li><a href="#">qwerty</a></li>
    </ul>
  </div>

I searched the web but haven’t found anything similar to this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your extra <li> tag is rendered by the browser as an empty <li> element (i.e. <li></li>). Thus, when it is looped over by your for loop, the following lines fail:

a = li[i].getElementsByTagName("a")[0];
if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {

because the empty li element doesn’t contain an a element, and thus the a variable is undefined, causing a.innerHTML to throw an error (since you can’t access a property on an undefined value).

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading