如何使用搜索参数搜索HTML表格数据

时间:2019-02-07 08:21:04

标签: javascript jquery

我有一个HTML表,其中填充了JSON数据, 我提供了一个搜索字段,该字段提供了搜索时的表数据, 现在我想做的是

  • 我有一个select下拉列表,其中包含表标题名称
  • 点击该选项后,我只想搜索该特定列
  • 假设这里我有一个列名为User Code,因此从下拉列表中,当用户选择用户代码并搜索表数据应仅填充用户代码的任何内容时
  • 我正在用tbody进行搜索
  • 当前我的搜索字段用于搜索整个表格

代码段

$(document).ready(function() {
  var tableValue = [{
      "Distributor Name": "MAIYAS RESTAURANTS PVT LTD",
      "User Name": "admin",
      "User LoginId": "admin",
      "User Password": "admin",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "MAIYAS RESTAURANTS PVT LTD",
      "User Name": "maiyas",
      "User LoginId": "maiyas",
      "User Password": "maiyas",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "CHEF BAKERS",
      "User Name": "cbadmin",
      "User LoginId": "cbadmin",
      "User Password": "cbadmin",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "CHEF BAKERS",
      "User Name": "cbaker",
      "User LoginId": "cbaker",
      "User Password": "cbaker",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "JAYANAGAR MAIYAS RESTAURANTS PVT LTD",
      "User Name": "jayanagar",
      "User LoginId": "jayanagar",
      "User Password": "jayanagar",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "MALLESHWARAM MAIYAS RESTAURANTS PVT LTD",
      "User Name": "malleswaram",
      "User LoginId": "malleswaram",
      "User Password": "malleswaram",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "KOLAR MAIYAS RESTAURANTS PVT LTD",
      "User Name": "kolar",
      "User LoginId": "kolar",
      "User Password": "kolar",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    }
  ]

  function addTable(tableValue) {
    var col = Object.keys(tableValue[0]);
    var countNum = col.filter(i => !isNaN(i)).length;
    var num = col.splice(0, countNum);
    col = col.concat(num);
    var table = document.createElement("table");
    var tr = table.insertRow(-1);
    for (var i = 0; i < col.length; i++) { //this one to make  thead
      var th = document.createElement("th");
      th.innerHTML = col[i];
      tr.classList.add("text-center");
      tr.appendChild(th);
    }
    for (var i = 0; i < tableValue.length; i++) { // thid one to make tbody
      tr = table.insertRow(-1);
      tr.classList.add("filterData"); //hear i am adding the class in body
      for (var j = 0; j < col.length; j++) {
        var tabCell = tr.insertCell(-1);
        var tabledata = tableValue[i][col[j]];
        if (tabledata && !isNaN(tabledata)) {
          tabledata = parseInt(tabledata);
          tabCell.classList.add("text-right");
        }
        tabCell.innerHTML = tabledata;
      }
      var divContainer = document.getElementById("table");
      divContainer.innerHTML = "";
      divContainer.appendChild(table);
      table.classList.add("table");
      table.classList.add("table-striped");
      table.classList.add("table-bordered");
      table.classList.add("table-hover");
    }
  }
  addTable(tableValue)

  $("#mySelect").on("change", function(e) {
    var header = this.value;
    alert(header)
    $("#myInput").on("keyup", function() {
      var q = $(this).val().toLowerCase();
      if (q === "") {
        $(".filterData").show();
        return true;
      }
      $(".filterData").hide().filter(function(i, el) {
        var d = $(el).text().trim().toLowerCase();
        console.log(q, d, d.indexOf(q));
        return (d.indexOf(q) > -1);
      }).show();
    });
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<select id="mySelect">
  <option disabled></option>
  <option>Distributor Name</option>
  <option>User Name</option>
  <option>User LoginId</option>
  <option>User Password</option>
  <option>User Role</option>
  <option>Active</option>
</select>
<input id="myInput" type="text" placeholder="Search..">
<div id="table"></div>

3 个答案:

答案 0 :(得分:1)

您不应在实际元素(即DOM)上进行搜索,因为这非常慢。考虑改为在初始数据数组上搜索并进行更改。让实际的TABLE只是数组当前状态的表示形式。这样,您的代码和逻辑将变得更简洁,更易于理解和维护,并且速度更快。

以下是代码段:

$(document).ready(function() {
var filters = {
  header: '',
  value: ''
}; 

var tableValue = [
  {
    isVisible: true,
    data: {
      "Distributor Name": "MAIYAS RESTAURANTS PVT LTD",
      "User Name": "admin",
      "User LoginId": "admin",
      "User Password": "admin",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
  },
  {
    isVisible: true,
    data: {
      "Distributor Name": "KOLAR MAIYAS RESTAURANTS PVT LTD",
      "User Name": "kolar",
      "User LoginId": "kolar",
      "User Password": "kolar",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    }
  }
];

function addTable(tableValue) {
  // you could also use these to construct dynamic select box
  var headers = Object.keys(tableValue[0].data); // or hardcode these somewhere

  // construct header
  var thead = '<tr><th>' + headers.join('</th><th>') + '</th></tr>';
  var tbody = '';

  for (var i = 0; i < tableValue.length; i++) { // thid one to make tbody
    if (!tableValue[i].isVisible) continue; // ignore non relevant items
    tbody += '<tr>';
    for (var header in tableValue[i].data) {
      tbody += '<td>' + tableValue[i].data[header] + '</td>';
    }
    tbody += '</tr>';
  }
  
  if (!tbody) { 
     tbody = '<tr><td colspan="'+headers.length+'">No results.</td></tr>';
  }
  
  document.getElementById("table").innerHTML = '<table class="table table-striped table-bordered table-hover">' + thead + tbody + '</table>';
}

function filterTable() {
  var re = new RegExp(filters.value, 'i');
  var matchContents = function(str) {
    return re.test(str);
  };

  tableValue.forEach(function(row) {
    var data = row.data;

    if (filters.header) {
      row.isVisible = matchContents(data[filters.header]);
    } else {
      for (var header in data) {
        if (matchContents(data[header])) {
          row.isVisible = true;
          return;
        }
      }
      row.isVisible = false;
    }
  });

  addTable(tableValue);
}

$("#mySelect").on("change", function(e) {
  filters.header = $(":eq("+this.selectedIndex+")", this).text();
  filterTable();
});

$("#myInput").on("keyup", function() {
  filters.value = $(this).val().toLowerCase();
  filterTable();
});

addTable(tableValue);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<select id="mySelect">
  <option></option>
  <option>Distributor Name</option>
  <option>User Name</option>
  <option>User LoginId</option>
  <option>User Password</option>
  <option>User Role</option>
  <option>Active</option>
</select>
<input id="myInput" type="text" placeholder="Search..">
<div id="table"></div>

我还简化了addTable()逻辑,这太复杂了。

答案 1 :(得分:1)

看看这段代码。

我将selectedIndex用作eq

如果启用第一个选项,他们可以在任何地方搜索

var tableValue = [{
    "Distributor Name": "MAIYAS RESTAURANTS PVT LTD",
    "User Name": "admin",
    "User LoginId": "admin",
    "User Password": "admin",
    "User role": "DISTRIBUTOR",
    "Active": "Y"
  },
  {
    "Distributor Name": "MAIYAS RESTAURANTS PVT LTD",
    "User Name": "maiyas",
    "User LoginId": "maiyas",
    "User Password": "maiyas",
    "User role": "DISTRIBUTOR",
    "Active": "Y"
  },
  {
    "Distributor Name": "CHEF BAKERS",
    "User Name": "cbadmin",
    "User LoginId": "cbadmin",
    "User Password": "cbadmin",
    "User role": "DISTRIBUTOR",
    "Active": "Y"
  },
  {
    "Distributor Name": "CHEF BAKERS",
    "User Name": "cbaker",
    "User LoginId": "cbaker",
    "User Password": "cbaker",
    "User role": "DISTRIBUTOR",
    "Active": "Y"
  },
  {
    "Distributor Name": "JAYANAGAR MAIYAS RESTAURANTS PVT LTD",
    "User Name": "jayanagar",
    "User LoginId": "jayanagar",
    "User Password": "jayanagar",
    "User role": "DISTRIBUTOR",
    "Active": "Y"
  },
  {
    "Distributor Name": "MALLESHWARAM MAIYAS RESTAURANTS PVT LTD",
    "User Name": "malleswaram",
    "User LoginId": "malleswaram",
    "User Password": "malleswaram",
    "User role": "DISTRIBUTOR",
    "Active": "Y"
  },
  {
    "Distributor Name": "KOLAR MAIYAS RESTAURANTS PVT LTD",
    "User Name": "kolar",
    "User LoginId": "kolar",
    "User Password": "kolar",
    "User role": "DISTRIBUTOR",
    "Active": "Y"
  }
]

function addTable(tableValue) {
  var $tbl = $("<table />", {"class": "table table-striped table-bordered table-hover"}),
      $thd = $("<thead/>"),
       $tb = $("<tbody/>"),
      $trh = $("<tr/>", {"class": "text-center"});

  $.each(Object.keys(tableValue[0]), function(_,val) {
    $("<th/>").html(val).appendTo($trh);
  });
  $trh.appendTo($thd);
  $.each(tableValue, function(_, item) {
    $tr = $("<tr/>", {"class": "filterData"});
    $.each(item, function(key,value) {
      $("<td/>", {"class": "text-right"}).html(value).appendTo($tr);
      $tr.appendTo($tb);
    });
  });
  $tbl.append($thd).append($tb);
  $("#table").html($tbl);
}
$(function() {

  addTable(tableValue)
  $("#myInput").on("input", function() {
    var q = $(this).val().toLowerCase();
    if (q === "") {
      $(".filterData").show();
      return true;
    }
    var fldIdx = $("#mySelect")[0].selectedIndex;
    $(".filterData").hide().filter(function(i, el) {
      var d = fldIdx === 0 ? $(el).text().trim().toLowerCase() : $("td", el).eq(fldIdx - 1).text().trim().toLowerCase()
      // console.log(q, d, d.indexOf(q));
      return (d.indexOf(q) > -1);
    }).show();
  });

  $("#mySelect").on("change", function(e) {
    $("#myInput").trigger("input");
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<select id="mySelect">
  <option>All</option>
  <option>Distributor Name</option>
  <option>User Name</option>
  <option>User LoginId</option>
  <option>User Password</option>
  <option>User Role</option>
  <option>Active</option>
</select>
<input id="myInput" type="text" placeholder="Search..">
<div id="table"></div>

答案 2 :(得分:0)

您可以将用户定义的(您自己的)columnName属性附加到您创建的每个单元DOM对象。然后,您可以在搜索功能doFilter中枚举单元格,并检查它们的columnName属性是否与当前过滤器字段匹配。

$(document).ready(function() {
  var tableValue = [{
      "Distributor Name": "MAIYAS RESTAURANTS PVT LTD",
      "User Name": "admin",
      "User LoginId": "admin",
      "User Password": "admin",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "MAIYAS RESTAURANTS PVT LTD",
      "User Name": "maiyas",
      "User LoginId": "maiyas",
      "User Password": "maiyas",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "CHEF BAKERS",
      "User Name": "cbadmin",
      "User LoginId": "cbadmin",
      "User Password": "cbadmin",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "CHEF BAKERS",
      "User Name": "cbaker",
      "User LoginId": "cbaker",
      "User Password": "cbaker",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "JAYANAGAR MAIYAS RESTAURANTS PVT LTD",
      "User Name": "jayanagar",
      "User LoginId": "jayanagar",
      "User Password": "jayanagar",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "MALLESHWARAM MAIYAS RESTAURANTS PVT LTD",
      "User Name": "malleswaram",
      "User LoginId": "malleswaram",
      "User Password": "malleswaram",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    },
    {
      "Distributor Name": "KOLAR MAIYAS RESTAURANTS PVT LTD",
      "User Name": "kolar",
      "User LoginId": "kolar",
      "User Password": "kolar",
      "User role": "DISTRIBUTOR",
      "Active": "Y"
    }
  ]

  function addTable(tableValue) {
    var col = Object.keys(tableValue[0]);
    var countNum = col.filter(i => !isNaN(i)).length;
    var num = col.splice(0, countNum);
    col = col.concat(num);
    var table = document.createElement("table");
    var tr = table.insertRow(-1);
    for (var i = 0; i < col.length; i++) { //this one to make  thead
      var th = document.createElement("th");
      th.innerHTML = col[i];
      tr.classList.add("text-center");
      tr.appendChild(th);
    }
    for (var i = 0; i < tableValue.length; i++) { // thid one to make tbody
      tr = table.insertRow(-1);
      tr.classList.add("filterData"); //hear i am adding the class in body
      for (var j = 0; j < col.length; j++) {
        var tabCell = tr.insertCell(-1);
        tabCell.columnName = col[j];
        var tabledata = tableValue[i][col[j]];
        if (tabledata && !isNaN(tabledata)) {
          tabledata = parseInt(tabledata);
          tabCell.classList.add("text-right");
        }
        tabCell.innerHTML = tabledata;
      }
      var divContainer = document.getElementById("table");
      divContainer.innerHTML = "";
      divContainer.appendChild(table);
      table.classList.add("table");
      table.classList.add("table-striped");
      table.classList.add("table-bordered");
      table.classList.add("table-hover");
    }
  }
  addTable(tableValue);

  function doFilter(filterField, q)
  {
      q = q.toLowerCase();

      if ((filterField === "") || (q === "")) {
        $(".filterData").show();
        return;
      }

      // we have something to filter
      $(".filterData").hide().filter(function(i, el) {
        var rowCells = el.cells;
        //console.log('el',el.cells, filterField, q);
        for (var ci = 0; ci < el.cells.length; ci++) {
          var cell = rowCells[ci];
          if (cell.columnName == filterField) {
            var d = $(cell).text().trim().toLowerCase();
            //console.log(q, d, d.indexOf(q));
            return (d.indexOf(q) > -1);
          }
        }
        return false;
      }).show();
  }

  $("#mySelect").on("change", function(e) {
    doFilter($("#mySelect").val(), $("#myInput").val());
  });

  $("#myInput").on("keyup", function() {
    doFilter($("#mySelect").val(), $("#myInput").val());
  });
});

在许多情况下,BTW将用户定义的属性附加到任何DOM对象的能力可以大大简化代码。例如,为了保持环境清洁,您可以决定将整个数据记录附加到tr。只是为了不干扰标准属性,您可以按照el.appData = { field1 : value1, ... }的方式进行操作,并以el.appData.field1的身份进行访问。在这种情况下,您将注入单个appData属性对象,该对象易于在您的代码中进行跟踪。