【问题标题】:I need to filter table cells in real time (in html jQuery)我需要实时过滤表格单元格(在 html jQuery 中)
【发布时间】:2017-04-15 02:39:32
【问题描述】:

搜索堆栈溢出我能够实时过滤行,但我需要更具体。 现在我正在使用这段代码:

HTML:

<input type="text" id="search" placeholder="Write here to filter">

脚本:

$(document).ready(function(){
    var $rows = $('#catalogo tbody tr');
    $rows.splice(0,1);
    $('#search').keyup(function() {
      var val = $.trim($(this).val()).replace(/ +/g, ' ').toLowerCase().split(' ');

      $rows.hide().filter(function() {
        var text = $(this).text().replace(/\s+/g, ' ').toLowerCase();
        var matchesSearch = true;
        $(val).each(function(index, value) {
          matchesSearch = (!matchesSearch) ? false : ~text.indexOf(value);
        });
        return matchesSearch;
      }).show();
});
});

基于此的脚本:How to perform a real time search and filter on a HTML table

我想做的是能够有 4 个不同的输入,每个输入过滤每行的第一、第二、第三和第四个单元格(能够按标题、作者、年份和最高价格进行过滤)。 我怎么能做到这一点?

【问题讨论】:

标签: javascript jquery html filter


【解决方案1】:

感谢 blackandorangecat 的链接,我设法把一些东西放在一起。

HTML:

<label class = "text">Título:<input type="text" id="stitulo" onkeyup="filter(this, 0)" style="margin: 0 auto;"/></label>
<label class = "text">Autor:<input type="text" id="sautor" onkeyup="filter(this, 1)" style="margin: 0 auto;"/></label>
<label class = "text">Año:<input type="text" id="sano" onkeyup="filter(this, 3)" size="1" style="margin: 0 auto;"/></label>
<label class = "text">Precio máximo:<input type="text" id="sprecio" onkeyup="filterNum(this, 4)" size="1" style="margin: 0 auto;"/></label>

JavaScript:

function filter(x, y) {
  // Declare variables 
  var input, filter, table, tr, td, i;
  input = x;
  filter = input.value.toUpperCase();
  table = document.getElementById("catalogo");
  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")[y];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
}

function filterNum(x, y) {
  // Declare variables 
  var input, filter, table, tr, td, i;
  input = x;
  if(input.value === "") {
      filter = 0.;
  } 
  else filter = parseFloat(input.value);
  table = document.getElementById("catalogo");
  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")[y];
    if (td) {
      if ((filter >= parseFloat(td.innerHTML)) || filter === 0) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
}

希望这对其他人也有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-08
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 2012-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多