如何使用jQuery制作下拉列表过滤器

时间:2018-02-20 15:19:58

标签: javascript jquery filter

我想让下拉表过滤依赖于item.id。我尝试了几种方法,但它们没有用。我想要的是根据item.id过滤表格。

它使用此代码,但当我尝试更改选定的值或项目时,它不起作用。请帮忙。

$("#filterText").change(function() {
  var rex = $('#filterText').val();

  if (rex == "/all/") {
    clearFilter()
  } else {
    var id = $('#' + rex);
    id.hide();
    // $('.toggle').filter(function () {
    //    return rex.test($(this).text());
    // }).show();
  }
});

function clearFilter() {
  $('#filterText').val('');
  $('.toggle').show();
}
<select id='filterText'>
  @foreach (var item in Model)
  {
    <option value="@item.ID">@item.Title.ToString()</option>
  }
</select>

<div class="panel-group" id="accordion">
  <div id="faqs" class="faqs">
    <table>
      @foreach (var item in Model) 
      { 
        foreach (var child in item.questions) 
        {
          <tr id="@item.ID" class="toggle faq faq-marketplace faq-authors">
            <td class="togglet">@child.Title</td>
            <td class="togglec">@child.Answer</td>
          </tr>
        } 
      }
    </table>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

您可以执行以下操作:

如果值不是全部,请选择所有tr并显示全部。然后,选择除值usine tr以外的所有其他.not()并隐藏。

$(function() {
  $("#filterText").change(function() {
    var rex = $('#filterText').val();
    if (rex != "all") $("table tr").show().not('#' + rex).hide();
    else $("table tr").show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id='filterText'>
   <option value="all"> All </option>
   <option value="1">Value 1</option>
   <option value="2">Value 2</option>
   <option value="3">Value 3</option>
</select>

<table>
  <tr id="1" class="toggle faq faq-marketplace faq-authors">
    <td class="togglet">Title 1</td>
    <td class="togglec">Whatever 1</td>
  </tr>
  <tr id="2" class="toggle faq faq-marketplace faq-authors">
    <td class="togglet">Title 2</td>
    <td class="togglec">Whatever 2</td>
  </tr>
  <tr id="3" class="toggle faq faq-marketplace faq-authors">
    <td class="togglet">Title 3</td>
    <td class="togglec">Whatever 3</td>
  </tr>
</table>

相关问题