首页 > 解决方案 > 带有搜索输入的 JQuery 过滤表

问题描述

我有 2 个过滤表的下拉列表。这些工作正常。它们根据选择显示/隐藏行。我还想添加一个搜索来进一步过滤行,但我无法让它工作。

例如,搜索需要考虑下拉选择。因此,如果 dropdown 1='Three' 和 dropdown 2='Four' (例如) - 返回 5 行。如果我开始在搜索框中输入“右”,那么应该会出现 2 行。当我退出搜索时,应该重新出现 5 行(下拉过滤器完好无损)

编码笔: https ://codepen.io/rblanc/pen/eYOEgXg

这是JQuery

$(function() {
  $('#archive, #type').change(function() {
    filterTable($('#archive').val(), $('#type').val());
  });
});

function filterTable(archive, entry) {
  var $rows = $('#filter tbody tr').show();

   if (archive == "one") {
    $rows.filter(":has(td:nth-child(4):contains('Two'))").hide()
    $rows.filter(":has(td:nth-child(4):contains('Three'))").hide()
  } else if (archive == "two") {
    $rows.filter(":has(td:nth-child(4):contains('One'))").hide()
    $rows.filter(":has(td:nth-child(4):contains('Three'))").hide()
  } else if (archive == "three") {
    $rows.filter(":has(td:nth-child(4):contains('One'))").hide()
    $rows.filter(":has(td:nth-child(4):contains('Two'))").hide()
  }

  if (entry == "one") {

    $rows.filter(":has(td:nth-child(6):contains('N'))").hide()
    $rows.filter(":has(td:nth-child(7):contains('Y'))").hide()
    $rows.filter(":has(td:nth-child(8):contains('Y'))").hide()

  } else if (entry == "two") {

    $rows.filter(":has(td:nth-child(6):contains('Y'))").hide()
    $rows.filter(":has(td:nth-child(7):contains('Y'))").hide()
    $rows.filter(":has(td:nth-child(8):contains('N'))").hide()

  } else if (entry == "three") {

    $rows.filter(":has(td:nth-child(6):contains('Y'))").hide()
    $rows.filter(":has(td:nth-child(7):contains('N'))").hide()
    $rows.filter(":has(td:nth-child(8):contains('Y'))").hide()

   } else if (entry == "four") {

    $rows.filter(":has(td:nth-child(6):contains('N'))").hide()
    $rows.filter(":has(td:nth-child(7):contains('Y'))").hide()
    $rows.filter(":has(td:nth-child(8):contains('N'))").hide()

   }
}

// SEARCH INPUT
$("#search").on("keyup", function() {
    var value = $(this).val();

    $("table tbody tr").each(function(index) {
        if (index !== 0) {

            $row = $(this);

            var id = $row.find("td:first").text();

            if (id.indexOf(value) !== 0) {
                $row.hide();
            }
            else {
                $row.show();
            }
        }
    });
});

标签: javascriptjqueryhtmlfiltering

解决方案


推荐阅读