Mezmerizer 9
Mezmerizer 9

Reputation: 53

Stuck on search js

function myFunction() {
    var input, filter, ul, li, a, i, txtValue;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    ul = document.getElementById("myUL");
    ul.style.display = "block";
    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";
        }
    }
}

This is the code I have for Search but it's not working the way I need it to.

Example:

The element I want to search for is "Water Purifier - New York".

I want it to filter it even when I type Water New in search, but it doesn't. Basically, search needs to look for all elements containing given words regardless of order of those words.

Upvotes: 2

Views: 70

Answers (1)

EugenSunic
EugenSunic

Reputation: 13693

Your example works fine, add an eventListener on input change and you should be able to filter out your records

Also adjusted the search criteria so that it renders elements based on the inserted letters.

For example:

1.) input: wtr; output: Water Purifier - New York, world trade render

2.) input: wtrp; output: Water Purifier - New York

function myFunction(e) {
  var input, filter, ul, li, a, i, txtValue;
  input = document.getElementById("myInput");
  filter = e.target.value.toUpperCase()
  ul = document.getElementById("myUL");
  ul.style.display = "block";
  li = ul.getElementsByTagName("li");
  for (i = 0; i < li.length; i++) {
    a = li[i].getElementsByTagName("a")[0];
    txtValue = a.textContent || a.innerText;
    if (filter.split('')
      .every(x => txtValue.toUpperCase().split('').some(y => y === x))) {
      li[i].style.display = "";
    } else {
      li[i].style.display = "none";
    }
  }
}

document.getElementById('search').addEventListener('input', (e) => {
  myFunction(e)
})
<ul id="myUL">
  <li><a href="#">Water Purifier - New York,</a></li>
  <li><a href="#">Poland</a></li>
  <li><a href="#">Something3</a></li>
  <li><a href="#">world trade render</a></li>
</ul>

<input id="search" type="text" />

Upvotes: 3

Related Questions