Search code examples
javascripthtmlsearchsearchbar

Filter/Search bar (list of <a> elements) - not working


I am trying to use this example by w3schools to add a search bar. I can't get it to work, I have changed it to match my elements but with no success. I have to have my js separate from the HTML document so no <script> My issue is that It does not work, and I do not know how to debug it. Here is my js file:

//search bar
function myFunction() {
// Declare variables
var input, filter, ul, div, li, a, span, i;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("container");
span = ul.getElementsByTagName('span');

// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < li.length; i++) {
    a = span[i].getElementsByTagName("a")[0];
    if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
        span[i].style.display = "";
    } else {
        span[i].style.display = "none";
    }
  }
}
document.getElementById('myInput').addEventListener('keyup', myFunction);

And my HTML file

<div class="container">
    <input type="text" id="myInput" placeholder="Search for names..">
    <div id="container">
        <span><a href="#" class="myButton" id="nico">Nico Nico Nii!!</a></span>
        <span><a href="#" class="myButton" id="redbone">Childish Gambino - Redbone</a></span>
        <span><a href="#" class="myButton" id="americaf">America F*ck Yeah!</a></span>
</div>
</div>

Solution

  • Firstly, you have a lot of unnecessary variables. You only need two, one to get the values of the list and the other to get value of filter. If there are more than one element, use class instead. See the working code below:

    //search bar
    function myFunction() {
    var input, filter;
    input = document.getElementsByClassName('myLinks');
    filter = document.getElementById('myInput').value.toUpperCase();
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < input.length; i++) {
        var currentElem = input[i];
        var currentElemChild = input[i].children[0]
        if (currentElemChild.innerHTML.toUpperCase().indexOf(filter) > -1) {
            currentElem.style.display = "";
        } else {
            currentElem.style.display = "none";
        }
      }
    }
    document.getElementById('myInput').addEventListener('keyup', myFunction);
    <div>
        <input type="text" id="myInput" placeholder="Search for names..">
        <ul id="container">
            <li class="myLinks"><a href="#" id="nico">Nico Nico Nii!!</a></li>
            <li class="myLinks"><a href="#" id="redbone">Childish Gambino - Redbone</a></li>
            <li class="myLinks"><a href="#" id="americaf">America F*ck Yeah!</a></li>
    </ul>
    </div>