Home > Article > Web Front-end > Using JavaScript to implement table filtering function
Use JavaScript to implement table filtering function
With the continuous development of Internet technology, tables have become a common way to display data on web pages. However, when the amount of data is huge, users often face difficulties in finding specific data. Therefore, adding filtering functions to tables so that users can quickly find the required data has become a requirement for many web designs. This article will introduce how to use JavaScript to implement table filtering function.
First, we need to have a form of data. The following is a simple example:
<table id="data-table"> <thead> <tr> <th>姓名</th> <th>年龄</th> <th>性别</th> <th>城市</th> </tr> </thead> <tbody> <tr> <td>张三</td> <td>25</td> <td>男</td> <td>北京</td> </tr> <tr> <td>李四</td> <td>30</td> <td>女</td> <td>上海</td> </tr> <tr> <td>王五</td> <td>28</td> <td>男</td> <td>广州</td> </tr> </tbody> </table>
Next, we need an input box for users to enter filter conditions. Use the following code to add an input box:
<input type="text" id="filter-input" placeholder="输入筛选条件">
Then, we need to write JavaScript code to implement the filtering function of the table. The code is as follows:
// 获取数据表格和筛选输入框 const table = document.querySelector('#data-table'); const filterInput = document.querySelector('#filter-input'); // 监听筛选输入框的输入事件 filterInput.addEventListener('input', () => { const filterValue = filterInput.value.toLowerCase(); // 获取输入框的值并转为小写 // 获取表格中的所有行 const rows = table.getElementsByTagName('tr'); // 遍历表格中的每一行,并根据筛选条件显示/隐藏行 for (let i = 0; i < rows.length; i++) { const row = rows[i]; const dataCells = row.getElementsByTagName('td'); let shouldShowRow = false; // 遍历当前行的每个单元格,检查是否有匹配的值 for (let j = 0; j < dataCells.length; j++) { const cell = dataCells[j]; const cellValue = cell.textContent.toLowerCase(); // 如果单元格的值与筛选条件匹配,显示该行 if (cellValue.includes(filterValue)) { shouldShowRow = true; } } // 根据shouldShowRow的值,显示/隐藏行 if (shouldShowRow) { row.style.display = ''; } else { row.style.display = 'none'; } } });
Now, when the user enters filter conditions in the input box, the table will show/hide the corresponding rows based on the conditions.
This article introduces how to use JavaScript to implement table filtering function. By adding filter input boxes and writing corresponding JavaScript code, we can make it easy for users to find specific data in the table. This has great practical value for data display and query of large tables. Hope this article helps you!
The above is the detailed content of Using JavaScript to implement table filtering function. For more information, please follow other related articles on the PHP Chinese website!