Search Box - Toggle Show/Hide Element using jQuery Tutorial

In this tutorial, I will show you how to create a simple search box that can toggle show/hide elements in your HTML. I will give you an idea of how to achieve this kind of feature using jQuery. The main goal of the said feature is to hide the element where the text does not include the word, character, or phrase in the search box.

Getting Started

The source code or scripts that I will be providing below is using Bootstrap v5 Framework for the design. You can download the said library at https://getbootstrap.com/docs/5.1/getting-started/download/. Also, kindly download also the jQuery library.

After that compile the libraries in a single directory which serves as your source code directory.

Lastly, the data I will be using for this tutorial are stored in a MySQL Database which means we will be using a local web server for this tutorial in oder to run PHP Sctipts. In my case, I am using XAMPP to run PHP Scripts in my local machine. You can download XAMPP at https://apachefriends.org.

Creating the Database

In a browser, browse the XAMPP's PHPMyAdmin i.e. http://localhost/phpmyadmin. Next, create a new database naming dummy_db. Then, navigate the page at the SQL Tab and copy/paste the mysql script below inside the provided text field in the page. Then click the "Go Button".

  1.   CREATE TABLE `members` (
  2.   `name` varchar(255) DEFAULT NULL,
  3.   `phone` varchar(100) DEFAULT NULL,
  4.   `email` varchar(255) DEFAULT NULL,
  5.   `address` varchar(255) DEFAULT NULL,
  6.   `country` varchar(100) DEFAULT NULL
  7.  
  8. INSERT INTO `members` (`id`, `name`, `phone`, `email`, `address`, `country`) VALUES
  9. (1, 'Tana Peck', '(869) 911-3643', '[email protected]', '596-229 Egestas Rd.', 'Germany'),
  10. (2, 'Ryan Cotton', '1-747-274-2733', '[email protected]', 'Ap #101-4741 Nibh. Avenue', 'Pakistan'),
  11. (3, 'Tate Simpson', '1-654-847-9768', '[email protected]', 'Ap #170-3218 Nascetur Street', 'United States'),
  12. (4, 'Imani Hogan', '1-564-774-9436', '[email protected]', 'P.O. Box 352, 273 Risus. Rd.', 'United Kingdom'),
  13. (5, 'Victoria Rogers', '1-424-109-8870', '[email protected]', 'Ap #700-7173 Varius. Avenue', 'New Zealand'),
  14. (6, 'Mohammad Bradley', '(487) 237-4830', '[email protected]', '316-9999 Nullam Ave', 'United Kingdom'),
  15. (7, 'Aiko Robbins', '(245) 413-5280', '[email protected]', '674-5559 Aliquam Av.', 'Norway'),
  16. (8, 'Aretha Wheeler', '1-973-454-4769', '[email protected]', '631-7616 Ante Rd.', 'Belgium'),
  17. (9, 'Cassandra Rivas', '(212) 758-1417', '[email protected]', '7578 Lorem, Ave', 'United Kingdom'),
  18. (10, 'Grant Owens', '1-667-444-0161', '[email protected]', 'Ap #635-4441 Blandit Road', 'Austria'),
  19. (11, 'Shelby Hendricks', '1-221-314-8372', '[email protected]', 'Ap #101-2708 Elementum Street', 'Sweden'),
  20. (12, 'Ignacia Maldonado', '(665) 362-4338', '[email protected]', '530-2752 Nunc St.', 'Colombia'),
  21. (13, 'Donovan Roy', '(337) 272-7464', '[email protected]', '1003 Turpis. Rd.', 'Italy'),
  22. (14, 'Lacota Berry', '(330) 994-8461', '[email protected]', 'P.O. Box 857, 7224 Tortor, St.', 'Italy'),
  23. (15, 'Malik Watts', '(324) 348-5007', '[email protected]', '734-9058 Eget Av.', 'Poland'),
  24. (16, 'Danielle Perkins', '1-221-846-1402', '[email protected]', '888-6975 Eu Rd.', 'Italy'),
  25. (17, 'Lester Mullen', '1-953-507-7968', '[email protected]', 'P.O. Box 597, 8840 Nonummy St.', 'Indonesia'),
  26. (18, 'Jemima Todd', '(409) 778-0721', '[email protected]', '213-7470 Sit Rd.', 'South Korea'),
  27. (19, 'Brody Mercer', '(149) 210-4385', '[email protected]', '513 Sed Road', 'Norway'),
  28. (20, 'Hashim Massey', '(623) 560-8376', '[email protected]', '479-6258 Ultrices Road', 'Indonesia'),
  29. (21, 'Hope Peterson', '(728) 572-2868', '[email protected]', '106 Dapibus Ave', 'Turkey'),
  30. (22, 'Luke Nash', '1-190-821-0114', '[email protected]', 'Ap #980-5182 Auctor Road', 'Indonesia'),
  31. (23, 'Gareth Vance', '1-787-264-3647', '[email protected]', 'Ap #345-7045 Elit. Street', 'New Zealand'),
  32. (24, 'Maya Cobb', '1-573-715-0453', '[email protected]', '643-7329 Tincidunt, Rd.', 'Chile'),
  33. (25, 'Daphne Hickman', '(311) 978-0663', '[email protected]', 'Ap #632-3067 Lorem, St.', 'United Kingdom');

Creating the Interface

Next, we will be creating the Interface of the simple application. This script contains a PHP Scripts including the database connection that allows us to fetch the data in the database. Save the file as index.php inside your source code folder.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3.     <meta charset="UTF-8">
  4.     <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title> Toogle Element</title>
  7.     <link rel="stylesheet" href="./css/bootstrap.min.css">
  8.     <script src="./js/jquery-3.6.0.min.js"></script>
  9.     <script src="./js/popper.min.js"></script>
  10.     <script src="./js/bootstrap.min.js"></script>
  11.     <script src="./js/script.js"></script>
  12.  
  13.     <style>
  14.         html,body{
  15.             height:100%;
  16.             width:100%;
  17.         }
  18.         main{
  19.             height:100%;
  20.             display:flex;
  21.             flex-flow:column;
  22.         }
  23.     </style>
  24. </head>
  25.     <main>
  26.     <nav class="navbar navbar-expand-lg navbar-dark bg-dark bg-gradient" id="topNavBar">
  27.         <div class="container">
  28.             <a class="navbar-brand" href="#">
  29.                 Toggle Show/Hide Elements
  30.             </a>
  31.         </div>
  32.     </nav>
  33.         <div class="container py-3" id="page-container">
  34.             <p>This is a simple program that toggles show/hide the elements if the keyword inputted on the search box exists in the element texts.</p>
  35.             <hr>
  36.             <div class="row justify-content-center">
  37.                 <div class="col-lg-5 col-md-8 col-sm-12 col-xs-12">
  38.                     <div class="form-group">
  39.                         <input type="search" id="keyword" class="form-control" placeholder="Searc here...">
  40.                     </div>
  41.                 </div>
  42.             </div>
  43.             <div class="clear-fix mb-3"></div>
  44.             <div class="row justify-content-center">
  45.                 <div class="col-lg-5 col-md-8 col-sm-12 col-xs-12">
  46.                     <div class="list-group" id="member-list">
  47.                         <?php
  48.                        $host = 'localhost';
  49.                        $username = 'root';
  50.                        $pw = '';
  51.                        $db_name = 'dummy_db';
  52.                        $conn = new mysqli($host,$username,$pw,$db_name);
  53.                        if(!$conn){
  54.                            die("Database Connection Failed. Error: ".$conn->error);
  55.                         }
  56.                         $sql = "SELECT * FROM `members` order by `name` asc";
  57.                         $qry = $conn->query($sql);
  58.                         while($row = $qry->fetch_assoc()):
  59.                         ?>
  60.                         <div class="list-group-item member-item">
  61.                             <h4 class="fw-bolder"><?= $row['name'] ?></h4>
  62.                             <div class="lh-1">
  63.                                 <small><span class="text-muted">Email:</span> <?= $row['email'] ?></small><br>
  64.                                 <small><span class="text-muted">Phone:</span> <?= $row['phone'] ?></small><br>
  65.                                 <small><span class="text-muted">Address:</span> <?= $row['address'] ?></small><br>
  66.                                 <small><span class="text-muted">Country</span> <?= $row['country'] ?></small>
  67.                             </div>
  68.                         </div>
  69.                         <?php endwhile; ?>
  70.                         <?php $conn->close(); ?>
  71.                     </div>
  72.                     <div class="col-lg-5 col-md-8 col-sm-12 col-xs-12 d-none text-center" id="NoResult"><i>No Result.</i></div>
  73.                 </div>
  74.             </div>
  75.         </div>
  76.     </main>
  77. </body>
  78. </html>

Creating the Main Script

Lastly, we will be creating the javascript file that contains the jquery scripts will toggle show/hide the elements when inputting a keyword in the searchbox. Make sure that the jquery link/source in the index.php is right according to the file path/location were you put the library file. Save the code below as script.js. Also make sure that this file will be loaded successfully in you index file.

  1. $(function() {
  2.     // Toggle Element that contains the keyword in the search box
  3.     $('#keyword').on('input', function() {
  4.         var keyword = $(this).val().toLowerCase();
  5.         $('#member-list .member-item').each(function() {
  6.             var txt = $(this).text().trim()
  7.             txt = txt.toLowerCase()
  8.             if (txt.includes(keyword) == true) {
  9.                 $(this).toggle(true)
  10.             } else {
  11.                 $(this).toggle(false)
  12.             }
  13.         })
  14.  
  15.         // Showing No result text if there's no result for keyword search
  16.         if ($('#member-list .member-item:visible').length == 0) {
  17.             if ($('#NoResult').hasClass('d-none'))
  18.                 $('#NoResult').removeClass('d-none')
  19.         } else {
  20.             if (!$('#NoResult').hasClass('d-none'))
  21.                 $('#NoResult').addClass('d-none')
  22.         }
  23.     })
  24. })

There you go. You can now test the source code on your end and see if it works perfectly or achieve the goal of this tutorial. If an error occurred on your end, review your source code and differentiate it from the scripts I provided above. I have also provided a working source code zip file in this article. You can download the source code below.

That's the end of this tutorial. I hope you will find this tutorial useful for your current and future web app projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)

Add new comment