Step 1: Set Up HTML Structure with a Search Input and Sample Table
We’ll create a basic HTML page with a search input and a sample table containing random data, such as employee information.
Employee Directory
| Employee ID | Name | Department | Position | Location |
|---|---|---|---|---|
| 101 | Alice Johnson | Finance | Accountant | New York |
| 102 | Bob Smith | Engineering | Software Developer | San Francisco |
| 103 | Carol White | Human Resources | HR Manager | Chicago |
| 104 | David Brown | Marketing | Brand Strategist | Los Angeles |
| 105 | Eve Black | Sales | Sales Manager | Miami |
Explanation of the Code
- Search Input:
- The input field with
id="searchInput"is placed above the table, where users can type their search terms. - The jQuery function will listen to this input field and use its value to filter the table rows.
- Sample Table:
- The table is filled with sample data, representing an employee directory.
- Each row in the
<tbody>contains random data, including Employee ID, Name, Department, Position, and Location.
- jQuery Search Script:
- This script listens for the
keyupevent on the search input. As the user types, it captures the search term, converts it to lowercase, and checks if any table row contains the search term. toggle(rowText.includes(searchTerm)): This line hides any rows that don’t include the search term and shows those that do.
How It Works
- Type in the Search Box: When you type into the search box, the script checks each table row for the presence of the search term.
- Filter Rows Dynamically: Rows that include the search term are shown, while rows that don’t are hidden. This filtering happens instantly without reloading the page.
Example Usage
- Typing “Finance” will only show rows containing the “Finance” department.
- Typing “Alice” will only display the row with the employee “Alice Johnson.”
- Typing “Manager” will show any rows that include the term “Manager” in any column, such as HR Manager or Sales Manager.
This setup provides a simple, client-side search function for any table, allowing for quick and efficient data filtering with minimal setup.