Using jQuery to search HTML text and show or hide accordingly

In this we will see how we could search the required text in an HTML and only view what we have found. The idea is to search a pattern as user types it and then ignore its case sensitivity and search the text. Once found display those blocks of data accordingly.
Copy and paste below code to search text from HTML and show that div only.
 
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
  $(document).ready(function(){
           //This will ignore case sensitivity of the test
            $.expr[":"].contains = $.expr.createPseudo(function(arg) {
                return function( elem ) {
                    return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
                };
            });
            
            $("#searchTextBox").keypress(function() {
              //This will chack the length of entered text
              if($("#searchTextBox").val().length > 0){
                $(".rows").css("display","none");
                var userSerarchField = $("#searchTextBox").val();
                //Will find and display only that div row
                $(".rows:contains('"+ userSerarchField +"')").css("display","block");
              } else {
                $(".rows").css("display","block");
              }              
            });
          });
</script>
</head>
<body>
<input type="text" id="searchTextBox">
<div class="divMain">
  <div class="rows rowOne">
    <h5>Test One</h5>
  </div>
  <div class="rows rowTwo">
    <h5>Test Two</h5>
  </div>
  <div class="rows rowThree">
    <h5>Test Three</h5>
  </div>
  <div class="rows rowFour">
    <h5>Test Four</h5>
  </div>
</div>
</body>
</html>
Author: 
Source: 
https://api.jquery.com/jQuery.contains/
https://css-tricks.com/snippets/jquery/make-jquery-contains-case-insensitive/

Add new comment