Skip to main content

How to use JavaScript to search for items in a list

  • //HTML Code 
    <div class="search-wrapper">
         <input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search here..." class="form-control search-box"/>
         <a class="csb-btn" href="javascript:void(0)" id="clearSearch"> <i class="fa fa-close"></i> </a>
    </div>
    <ul id="myUL">
      <li><a href="javascript:void(0)">Adele</a></li>
      <li><a href="javascript:void(0)">Agnes</a></li>
       <li><a href="javascript:void(0)">Billy</a></li>
      <li><a href="javascript:void(0)">Bob</a></li>
       <li><a href="javascript:void(0)">Calvin</a></li>
      <li><a href="javascript:void(0)">Christina</a></li>
      <li><a href="javascript:void(0)">Cindy</a></li>
    </ul>
    //Javascript Code
    <script>
    function myFunction() {
        var input, filter, ul, li, a, i, txtValue;
        input = document.getElementById('myInput');
        filter = input.value.toUpperCase();
        ul = document.getElementById("myUL");
        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";
            }
        }
        if(input.value.length > 0) {
            $('#clearSearch').css("display","block");
        } else{
            $('#clearSearch').css("display","none");
        }
    }
    //Clear input text on click 
    $("#clearSearch").on('click', function(e){
        $(this).hide();
        $("#myInput").val('');
        myFunction();
    })  
    </script>
    
  • Back to code snippet queries related javascript