如何实现大小写不敏感的表格过滤?现有代码为大小写敏感
Case-Insensitive Table Filter with jQuery
Got it, let's fix that case-sensitive filtering issue for your jQuery table filter. The core problem with your current code is that indexOf() does an exact case match—so we just need to normalize both the table cell content and input values to the same case (lowercase or uppercase) before comparing them.
Here's the updated, case-insensitive version of your code:
var $rows = $('tbody > tr'), $filters = $('#filter_table input'); $filters.on("keyup", function () { var $i = $filters.filter(function () { return $.trim(this.value).length > 0; }), len = $i.length; if (len === 0) return $rows.show(); var cls = '.' + $i.map(function () { return this.className }).get().join(',.'); $rows.hide().filter(function () { return $('td', this).filter(cls).filter(function () { // Normalize both content and input value to lowercase for case-insensitive matching var content = $.trim(this.textContent).toLowerCase(), inputVal = $.trim($i.filter('.' + this.className).val()).toLowerCase(); return content.indexOf(inputVal) > -1; }).length === len; }).show(); });
Key Changes Explained:
- Case Normalization: We convert both the table cell's text content and the input's value to lowercase with
toLowerCase(). This ensures matches work no matter if the user types uppercase or lowercase characters. - Whitespace Cleanup: I added
$.trim()to the cell content (alongside the input value) to avoid false misses caused by extra spaces in table cells. - Preserved Original Logic: All your existing functionality—like filtering tied to input classes, showing all rows when no filters are active—stays intact; we only adjusted the matching step.
If you'd rather use uppercase for normalization instead, just swap toLowerCase() with toUpperCase() in both spots; it’ll work the same way.
内容的提问来源于stack exchange,提问作者Darsil
相关产品推荐
相关产品推荐

