纯JavaScript实现Date Picker过滤HTML表格问题排查
表格日期过滤功能修复方案
问题描述
现有HTML表格过滤代码,姓名、数字、字母过滤功能正常,但日期选择器过滤失效。需要实现:
- 选择2023年相关日期时,仅显示表格中2023年的条目
- 选择具体日期(如01/01/1990)时,仅显示对应行
现有代码
表格结构
<div class="s-table-container"> <table class="s-table" id="MyTable"> <thead> <tr> <th>Name</th> <th>Date</th> </tr> </thead> <tbody> <tr> <td>John</td> <td>01/01/2023</td> </tr> <tr> <td>Adam</td> <td>06/12/1990</td> </tr> </tbody> </table> </div>
(注:原表格缺少id="MyTable",需补上才能被JS正常获取)
日期输入HTML
<label for="date">Filter By Date:</label> <input type="date" id="date" name="date">
原问题JS代码
if (document.getElementById('date').checked) { var input, filter, table, tr, td, i, txtValue; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); table = document.getElementById("MyTable"); tr = table.getElementsByTagName("tr"); // Loop through all table rows, and hide those who don't match the search query for (i = 0; i < tr.length; i++) { td = tr[i].getElementsByTagName("td")[3]; // change number to any other number to target column for table search if (td) { txtValue = td.textContent || td.innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { tr[i].style.display = ""; } else { tr[i].style.display = "none"; } } } }
错误分析
- 判断条件错误:
<input type="date">没有checked属性,应该判断输入值是否非空 - 输入框获取错误:错误获取了
myInput元素,实际应该获取date输入框 - 列索引错误:日期列是表格第2列(从0开始计数),原代码用了
[3],超出范围 - 日期格式不匹配:
date输入框返回格式为YYYY-MM-DD,但表格中日期是DD/MM/YYYY,直接字符串匹配会失败 - 匹配逻辑不满足需求:原代码仅做字符串包含匹配,无法实现年份或精确日期的过滤
修复后的JS代码
// 监听日期输入框的变化事件 document.getElementById('date').addEventListener('input', function() { const dateInput = this; const filterDate = dateInput.value; // 格式为YYYY-MM-DD const table = document.getElementById("MyTable"); const trList = table.querySelectorAll("tbody tr"); if (!filterDate) { // 输入为空时显示所有行 trList.forEach(tr => tr.style.display = ''); return; } // 提取输入日期的年份 const filterYear = filterDate.split('-')[0]; trList.forEach(tr => { const dateTd = tr.querySelector('td:nth-child(2)'); // 日期列是第2列(从1开始计数) if (!dateTd) return; const tableDateStr = dateTd.textContent.trim(); // 将表格中的DD/MM/YYYY转换为YYYY-MM-DD,方便比较 const [day, month, year] = tableDateStr.split('/'); const formattedTableDate = `${year}-${month.padStart(2, '0')}-${day.padStart(2, '0')}`; // 判断:精确匹配日期 或者 年份匹配 const isMatch = formattedTableDate === filterDate || year === filterYear; tr.style.display = isMatch ? '' : 'none'; }); });
修复说明
- 事件监听:改为监听日期输入框的
input事件,实时响应输入变化 - 格式统一:将表格中的
DD/MM/YYYY日期转换为YYYY-MM-DD,和输入框返回格式对齐 - 匹配逻辑:同时支持精确日期匹配和年份匹配,满足需求
- 索引修正:通过
nth-child(2)准确获取日期列,避免索引混乱 - 空值处理:输入为空时自动显示所有行,提升用户体验
内容的提问来源于stack exchange,提问作者Baa My
相关产品推荐
相关产品推荐

