J'ai un tableau HTML que je remplis avec des données JSON, il y a un champ de recherche que j'ai fourni qui donne les données de table lors de la recherche, Maintenant, ce que j'essaye de faire est
select qui est composé de noms d'en-tête de tableau Code utilisateur , donc dans la liste déroulante lorsque l'utilisateur sélectionne le code utilisateur et recherche n'importe quoi, les données de la table doivent être renseignées pour le code utilisateur uniquement Extrait de code
<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>
$(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();
});
});
});
3 Réponses :
Vous ne devriez pas faire la recherche sur les éléments réels (sur le DOM), car c'est TRÈS lent. Envisagez plutôt de rechercher et d'apporter des modifications sur le tableau de données initial. Soit le TABLE réel une simple représentation du tableau dans son état actuel. Ensuite, votre code et votre logique deviendront plus propres, plus faciles à comprendre et à maintenir, et beaucoup plus rapidement.
Voici l'extrait de code:
<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>
$(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);
});
J'ai aussi un peu simplifié la logique addTable () , c'était trop compliqué.
Je ne suis pas sûr de pouvoir convenir que la mise à jour du DOM est plus rapide que de le cacher et de l'afficher
Wonna jsPerf l'affaire? :)
N'hésitez pas :) Mais sur une table BEAUCOUP plus grande que celle ci-dessus. Il y aura près de 0 différence sur une telle table
Non ... Je sais que ce sera plus rapide et dans le scénario du monde réel, je l'aurais mis sur quelque chose comme ReactJS et activerais le fenêtrage sur cette table. Vous ne pouvez pas nier que la logique que j'ai montrée ici est beaucoup plus simple et claire, n'est-ce pas?
C'est plus propre. Mes doigts me démangeaient aussi pour affiner l'addTable
@jayarjo car je suis nouveau dans ce domaine, comment puis-je rendre cela encore plus mince (addTable)
Jetez un œil à ce code.
J'utilise le selectedIndex comme eq
Si vous activez la première option, ils peuvent rechercher n'importe où
<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>
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");
});
});
monsieur, comment puis-je rendre cet addTable plus mince, car je suis nouveau dans ce domaine, je n'ai que cette connaissance
J'ai changé l'addTable pour utiliser jQuery aussi
Vous pouvez attacher la propriété columnName définie par l'utilisateur (votre propre) à chaque objet DOM de cellule que vous créez. Ensuite, vous pouvez énumérer les cellules dans la fonction de recherche doFilter et vérifier si la propriété columnName correspond au champ de filtre actuel.
$(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());
});
});
La capacité BTW d'attacher des propriétés définies par l'utilisateur à n'importe quel objet DOM dans de nombreux cas peut simplifier considérablement le code. Juste pour garder les choses propres, vous pouvez décider de joindre un enregistrement de données entier au tr par exemple. Juste pour ne pas interférer avec les propriétés standard, vous pouvez le faire en face de el.appData = {field1: value1, ...} , et accéder en tant que el.appData.field1 code >. Dans ce cas, vous injectez un seul objet de propriété appData facile à retrouver dans votre code.