How To Search Html Table Data With Search Parameters
Solution 1:
Have a look at this code.
I use the selectedIndex as eq
If you enable the first option, they can search anywhere
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>
Solution 2:
You should not do the searching on the actual elements (on the DOM that is), 'cause it is VERY slow. Consider searching and making changes on the initial data array instead. Let the actual TABLE
be a mere representation visualization of the array in it's current state. Then your code and logic will become cleaner, easier to comprehend and maintain, and much MUCH faster.
Here's the snippet:
$(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>
I also somewhat simplified addTable()
logic, it was over complicated.
Solution 3:
You may attach user defined (your own) columnName
property to each cell DOM object you create. Then, you can enumerate cells in search function doFilter
and check if they columnName
property match current filter field.
$(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 ability to attach user-defined properties to any DOM object in many cases may simplify code dramatically. Just to keep things clean, you may decide to attach whole data record to the tr
for example. Just to not interfere with standard properties, you may do it in facion of el.appData = { field1 : value1, ... }
, and access as el.appData.field1
. In that case you inject single appData
property object that easy to track down in your code.
Post a Comment for "How To Search Html Table Data With Search Parameters"