Bemwa Malak
Bemwa Malak

Reputation: 1349

How to make a search list in which element is only shown when user search for its exact value

So, I have this html code to show a list of numbers:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="search">

<ul id="myUL">
  <li><a href="#">006372145</a></li>
  <li><a href="#">00021030</a></li>

  <li><a href="#">9123981283</a></li>
  <li><a href="#">190238120983</a></li>

  <li><a href="#">128378</a></li>
  <li><a href="#">1298488</a></li>
  <li><a href="#">12983498</a></li>
</ul>

And there is a search bar which a user can type text into. This is the JS code:

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

    if(input.value.length == 0){
        ul.style.display = "none";
        return;
    }else{
        ul.style.display = "block";
    }
    // Loop through all list items, and hide those who don't match the search query
    for (i = 0; i < li.length; i++) {
        a = li[i].getElementsByTagName("a")[0];
        if (a.innerHTML.toUpperCase().indexOf(filter) == 0) {
            li[i].style.display = "block";
        } 
        else {
            li[i].style.display = "none";
        }

    }
  }

It filters the search input to finally match a number but I am trying to make it only show the exact same number without filtering the rest of numbers to see if there is any matching.

For example, I input "00" and no number shows because it's not in the list. But if I typed an exact match to a number in the list it shows then.

Upvotes: 0

Views: 474

Answers (1)

smacaz
smacaz

Reputation: 168

function applyFilter(userInput){
    /*
      Use css to set the display to none first
    */
    var options = document.querySelectorAll("#myUL > a");
    for(var i = 0; i < options.length; i++){
        if(options[i].textContent.trim() == userInput.trim()){
            // You can also convert to lowercase for more accurate result
            options[i].style.display = "inline";
        }
    }
}

Upvotes: 2

Related Questions