mercredi 25 septembre 2019

Filtering a List by a Text Field

I have a created a small app that helps me be more productive at work. It filters a list of tags by their text contents. It currently works great for finding contiguous lines of text, but I would prefer to re-implement it as a filter that works for non-contiguous combinations of text.

For example, if the string inside the tag is "Appleville, MN", the current filter will find it if you type in "Apple" or "Appleville" or "App", but I want to be able to filter successfully with input such as "App MN".

Could anyone point me in the right direction? I'm not sure what exact algorithm I need to go with. Thanks!

PS: I've included some code below with examples of the kind of search items I am filtering, the current filter function, as well as the search field.

<ul id="itemList">
      <li onclick=applevilleMN()><a href="#" >Appleville, MN</a></li>
      <li onclick=orangevilleOR()><a href="#" >Orangeville, OR</a></li>
      <li onclick=kiwivilleCA()><a href="#" >Kiwiville, CA</a></li>
      <li onclick=bananavilleCA()><a href="#" >Bananaville, CA</a></li>
</ul>
function filterList() {
    var input, filter, ul, li, a, i, txtValue;
    input = document.getElementById('myInput');
    filter = input.value.toUpperCase();
    ul = document.getElementById("itemList");
    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";
      }
    }
  }
<input type="text" id="myInput" onkeyup="filterList()" placeholder="Search list.." >



Aucun commentaire:

Enregistrer un commentaire