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".
- (3, 'Tate Simpson', '1-654-847-9768', '[email protected]', 'Ap #170-3218 Nascetur Street', 'United States'),
- (4, 'Imani Hogan', '1-564-774-9436', '[email protected]', 'P.O. Box 352, 273 Risus. Rd.', 'United Kingdom'),
- (5, 'Victoria Rogers', '1-424-109-8870', '[email protected]', 'Ap #700-7173 Varius. Avenue', 'New Zealand'),
- (6, 'Mohammad Bradley', '(487) 237-4830', '[email protected]', '316-9999 Nullam Ave', 'United Kingdom'),
- (11, 'Shelby Hendricks', '1-221-314-8372', '[email protected]', 'Ap #101-2708 Elementum Street', 'Sweden'),
- (14, 'Lacota Berry', '(330) 994-8461', '[email protected]', 'P.O. Box 857, 7224 Tortor, St.', 'Italy'),
- (17, 'Lester Mullen', '1-953-507-7968', '[email protected]', 'P.O. Box 597, 8840 Nonummy St.', 'Indonesia'),
- (20, 'Hashim Massey', '(623) 560-8376', '[email protected]', '479-6258 Ultrices Road', 'Indonesia'),
- (23, 'Gareth Vance', '1-787-264-3647', '[email protected]', 'Ap #345-7045 Elit. Street', 'New Zealand'),
- (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.
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="./css/bootstrap.min.css">
- <style>
- html,body{
- height:100%;
- width:100%;
- }
- main{
- height:100%;
- display:flex;
- flex-flow:column;
- }
- </style>
- </head>
- <body>
- <main>
- <nav class="navbar navbar-expand-lg navbar-dark bg-dark bg-gradient" id="topNavBar">
- <div class="container">
- <a class="navbar-brand" href="#">
- Toggle Show/Hide Elements
- </a>
- </div>
- </nav>
- <div class="container py-3" id="page-container">
- <hr>
- <div class="row justify-content-center">
- <div class="col-lg-5 col-md-8 col-sm-12 col-xs-12">
- <div class="form-group">
- <input type="search" id="keyword" class="form-control" placeholder="Searc here...">
- </div>
- </div>
- </div>
- <div class="row justify-content-center">
- <div class="col-lg-5 col-md-8 col-sm-12 col-xs-12">
- <div class="list-group" id="member-list">
- <?php
- $host = 'localhost';
- $username = 'root';
- $pw = '';
- $db_name = 'dummy_db';
- $conn = new mysqli($host,$username,$pw,$db_name);
- if(!$conn){
- die("Database Connection Failed. Error: ".$conn->error);
- }
- $sql = "SELECT * FROM `members` order by `name` asc";
- $qry = $conn->query($sql);
- while($row = $qry->fetch_assoc()):
- ?>
- <div class="list-group-item member-item">
- <div class="lh-1">
- </div>
- </div>
- <?php endwhile; ?>
- <?php $conn->close(); ?>
- </div>
- </div>
- </div>
- </div>
- </main>
- </body>
- </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.
- $(function() {
- // Toggle Element that contains the keyword in the search box
- $('#keyword').on('input', function() {
- var keyword = $(this).val().toLowerCase();
- $('#member-list .member-item').each(function() {
- var txt = $(this).text().trim()
- txt = txt.toLowerCase()
- if (txt.includes(keyword) == true) {
- $(this).toggle(true)
- } else {
- $(this).toggle(false)
- }
- })
- // Showing No result text if there's no result for keyword search
- if ($('#member-list .member-item:visible').length == 0) {
- if ($('#NoResult').hasClass('d-none'))
- $('#NoResult').removeClass('d-none')
- } else {
- if (!$('#NoResult').hasClass('d-none'))
- $('#NoResult').addClass('d-none')
- }
- })
- })
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
- 459 views