Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
How to Append Header to a HTML Table in JavaScript ?
Next article icon

How to Create a Filter Table with JavaScript?

Last Updated : 16 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Filter tables are commonly used in web applications to organize and display tabular data efficiently. It allows users to search and filter through large datasets easily. In this tutorial, we will go through the steps to create a filter table with JavaScript.

Approach

  • First, create the basic HTML structure with a container for the table, and an input field for searching, and the table itself with headers and data rows.
  • Then use the CSS style to enhance the appearance of the table, including style for the input field, table headers, alternating row colors.
  • Use the JavaScript code to handle user input in the search field. And add a event listener in it and handle the "input" event.
  • Filter the table rows based on the search query entered by the user. Display the additional message "no data is found".

Example: The example code below shows how to create a filter table with JavaScript.

HTML
<!DOCTYPE html> <html lang="en">  <head>     <meta charset="UTF-8">     <meta name="viewport"            content="width=device-width, initial-scale=1.0">     <title>Filterable Table</title>     <link rel="stylesheet" href="style.css"> </head>  <body>      <div class="container">         <h1 class="main-heading">             How to Create a Filter Table with JavaScript         </h1>         <input type="text"                id="searchInput"                 placeholder="Search...">         <table id="dataTable">             <thead>                 <tr>                     <th>Name</th>                     <th>Age</th>                     <th>City</th>                 </tr>             </thead>             <tbody>                 <tr>                     <td>Priya</td>                     <td>30</td>                     <td>India</td>                 </tr>                 <tr>                     <td>Jane Smith</td>                     <td>25</td>                     <td>Los Angeles</td>                 </tr>                 <tr>                     <td>Antoine</td>                     <td>34</td>                     <td>France</td>                 </tr>                 <tr>                     <td>Yuki</td>                     <td>30</td>                     <td>USA</td>                 </tr>                 <tr>                     <td>Maria</td>                     <td>27</td>                     <td>Brazil</td>                 </tr>                 <tr>                     <td> Ivan</td>                     <td>22</td>                     <td>Russia</td>                 </tr>                 <tr>                     <td>John Doe</td>                     <td>30</td>                     <td>New York</td>                 </tr>             </tbody>         </table>         <span id="noMatch" style="display:none;">             No matching data is found !         </span>     </div>     <script src="script.js"></script> </body>  </html> 
CSS
/* style.css */ body {     font-family: Arial, sans-serif;     background-color: #f7f7f7;     margin: 0;     padding: 0; }  .container {     max-width: 800px;     margin: 50px auto;     padding: 20px;     background-color: #ffffff;     border-radius: 8px;     box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); }  .main-heading {     text-align: center;     margin-bottom: 20px;     color: #0ef61a; }  #searchInput {     margin-bottom: 10px;     padding: 8px;     width: 20%;     box-sizing: border-box; }  table {     width: 100%;     border-collapse: collapse; }  #dataTable td, #dataTable th {     border: 1px solid #ddd;     padding: 8px; }  #dataTable th {     padding-top: 12px;     padding-bottom: 12px;     text-align: left;     background-color: #0ef61a;     color: white; }  #dataTable tr:nth-child(even) {     background-color: #dbe0de; }  #noMatch {     color: red;     margin-top: 2.5rem;     margin-left: 17rem;     font-size: 20px; } 
JavaScript
/** script.js **/ let input = document.getElementById('searchInput'); let table = document.getElementById('dataTable'); let rows = table.getElementsByTagName('tr'); let noMatchMessage = document.getElementById('noMatch');  input.addEventListener('input', function () {     let filter = input         .value         .toLowerCase();     let matchFound = false;      for (let i = 1; i < rows.length; i++) {         let row = rows[i];         let cells = row             .getElementsByTagName('td');         let found = false;          for (let j = 0; j < cells.length; j++) {             let cell = cells[j];             if (cell.textContent.toLowerCase().indexOf(filter) > -1) {                 found = true;                 matchFound = true;                 break;             }         }          if (found) {             row.style.display = '';         } else {             row.style.display = 'none';         }     }      if (!matchFound) {         noMatchMessage.style.display = 'block';     } else {         noMatchMessage.style.display = 'none';     } }); 

Output:


Next Article
How to Append Header to a HTML Table in JavaScript ?
author
skaftafh
Improve
Article Tags :
  • JavaScript
  • Web Technologies
  • CSS

Similar Reads

  • Create a Sortable and Filterable Table using JavaScript
    In this article, we will demonstrate how to create a sortable and filtrable table using JavaScript. This custom table will have the functionality of editing or removing individual items along with sorting and filtering items according to different fields. Also, a form is attached so that the user ca
    6 min read
  • How to Filter an Array in JavaScript ?
    The array.filter() method is used to filter array in JavaScript. The filter() method iterates and check every element for the given condition and returns a new array with the filtered output. Syntax const filteredArray = array.filter( callbackFunction ( element [, index [, array]])[, thisArg]);Note:
    2 min read
  • How to filter Nested Array using Key in JavaScript ?
    Filtering a nested array in JavaScript involves the process of selectively extracting elements from an array of objects, where each object contains another array. We will discuss how can we filter Nested Array using the key in JavaScript. Filtering a nested array based on a key in JavaScript can be
    3 min read
  • How to Append Header to a HTML Table in JavaScript ?
    JavaScript allows us to dynamically modify the structure of a table based on user interaction or other dynamic events. Here we will use JavaScript to dynamically create a Header row and then append it to the HTML table. ApproachIn this approach, we are using create elements along with DOM manipulati
    3 min read
  • How to Create an HTML Table from an Object Array Using JavaScript ?
    Tables are a fundamental part of web development, and displaying data in a structured manner is a common requirement. JavaScript provides a powerful way to dynamically generate HTML content, making it easy to create tables from object arrays. Table of Content Using innerHTML propertyUsing appendChil
    2 min read
  • JavaScript Array filter() Method
    The filter() method creates a new array containing elements that satisfy a specified condition. This method skips empty elements and does not change the original array. Create a new array consisting of only those elements that satisfy the condition checked by canVote() function. [GFGTABS] JavaScript
    3 min read
  • How to create a table in ReactJS ?
    In ReactJS, tables are commonly used to display data in rows and columns. Tables can be static, where data is hardcoded, or dynamic, where data is passed from an array or fetched from an API. React makes it simple to create interactive and dynamic tables, with additional features such as sorting, pa
    6 min read
  • Java Servlet Filter with Example
    A filter is an object that is invoked at the preprocessing and postprocessing of a request on the server, i.e., before and after the execution of a servlet for filtering the request. Filter API (or interface) includes some methods which help us in filtering requests. To understand the concept of Fil
    4 min read
  • How to export HTML table to CSV using JavaScript ?
    Comma Separated Values or CSV is a type of text file where each value is delimited by a comma. CSV files are very useful for the import and export of data to other software applications. Sometimes while developing web applications, you may come into a scenario where you need to download a CSV file c
    6 min read
  • How to filter nested objects in JavaScript?
    The filter() method creates a new array with all elements that pass the test implemented by the provided function. Below are the approaches used to filter nested objects in JavaScript: Table of Content Using filter() methodUsing some() method Method 1: Using filter() method Example: This approach us
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences