Search code examples
javascriptindexofstartswith

Filter a list by the first letter(s)


I have a list of suburbs which I am filtering with the following. I works great but I'd like it to filter from the starting letters rather than matching any letters.

I feel like something like this should work but hasn't helped

if (txtValue.toUpperCase().indexOf(filter) === 0)

if (txtValue.toUpperCase().startsWith(filter))


function filterFunction() {
  var input, filter, ul, li, a, i;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  div = document.getElementById("mainNav");
  a = div.getElementsByTagName("li");
  for (i = 0; i < a.length; i++) {
    txtValue = a[i].textContent || a[i].innerText;
    if (txtValue.toUpperCase().indexOf(filter) > -1) {
      a[i].style.display = "";
    } else {
      a[i].style.display = "none";
    }
  }
}

<ul class="nav nav-pills" id="mainNav">
  <input type="text" placeholder="Search..." id="myInput" onkeyup="filterFunction()" style="padding: 10px; background-color:#343434; border: 0px; color: white;">
                                          
  <?php include_once( 'suburbs.php' );?>
                  
</ul>

Solution

  • Seems to be working fine for me.

    function filterFunction() {
      var input, filter, ul, li, a, i;
      input = document.getElementById("myInput");
      filter = input.value.toUpperCase();
      div = document.getElementById("mainNav");
      a = div.getElementsByTagName("li");
      for (i = 0; i < a.length; i++) {
        txtValue = a[i].textContent || a[i].innerText;
        if (txtValue.toUpperCase().startsWith(filter)) {
          a[i].style.display = "";
        } else {
          a[i].style.display = "none";
        }
      }
    }
    <input id="myInput" />
    
    <div id="mainNav">
      <li>test1</li>
      <li>test2</li>
      <li>atcbjgjhg</li>
      <li>something</li>
    </div>
    
    <button onclick="filterFunction()">
      Filter
    </button>