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', 'nullam.susc[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. html,body{
  14. height:100%;
  15. width:100%;
  16. }
  17. main{
  18. height:100%;
  19. display:flex;
  20. flex-flow:column;
  21. }
  22. </style>
  23. </head>
  24. <main>
  25. <nav class="navbar navbar-expand-lg navbar-dark bg-dark bg-gradient" id="topNavBar">
  26. <div class="container">
  27. <a class="navbar-brand" href="#">
  28. Toggle Show/Hide Elements
  29. </a>
  30. </div>
  31. </nav>
  32. <div class="container py-3" id="page-container">
  33. <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>
  34. <hr>
  35. <div class="row justify-content-center">
  36. <div class="col-lg-5 col-md-8 col-sm-12 col-xs-12">
  37. <div class="form-group">
  38. <input type="search" id="keyword" class="form-control" placeholder="Searc here...">
  39. </div>
  40. </div>
  41. </div>
  42. <div class="clear-fix mb-3"></div>
  43. <div class="row justify-content-center">
  44. <div class="col-lg-5 col-md-8 col-sm-12 col-xs-12">
  45. <div class="list-group" id="member-list">
  46. <?php
  47. $host = 'localhost';
  48. $username = 'root';
  49. $pw = '';
  50. $db_name = 'dummy_db';
  51. $conn = new mysqli($host,$username,$pw,$db_name);
  52. if(!$conn){
  53. die("Database Connection Failed. Error: ".$conn->error);
  54. }
  55. $sql = "SELECT * FROM `members` order by `name` asc";
  56. $qry = $conn->query($sql);
  57. while($row = $qry->fetch_assoc()):
  58. ?>
  59. <div class="list-group-item member-item">
  60. <h4 class="fw-bolder"><?= $row['name'] ?></h4>
  61. <div class="lh-1">
  62. <small><span class="text-muted">Email:</span> <?= $row['email'] ?></small><br>
  63. <small><span class="text-muted">Phone:</span> <?= $row['phone'] ?></small><br>
  64. <small><span class="text-muted">Address:</span> <?= $row['address'] ?></small><br>
  65. <small><span class="text-muted">Country</span> <?= $row['country'] ?></small>
  66. </div>
  67. </div>
  68. <?php endwhile; ?>
  69. <?php $conn->close(); ?>
  70. </div>
  71. <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>
  72. </div>
  73. </div>
  74. </div>
  75. </main>
  76. </body>
  77. </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

CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.
1 + 3 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.