Reputation: 850
I have made a script to find strings in table. When it finds it shows the row otherwise hide it. It is working perfectly in Chrome but it is some what lagging in Firefox and Internet Explorer. Is this code good or can it be better ?
$("#searchValue").keyup(function() {
var table = $(this).siblings('table').not(':hidden');
var name = $("#searchValue").val();
if (name === "") {
$(table).find('tr').show();
$(table).trigger('update');
}
else {
name = name.toLowerCase();
var trs = $(table).find('tr').not(':first');
trs.each(function() {
var tr = $(this);
var count = ($(tr).children('td').length);
var suc = -1;
for (var i = 0; i < count; i++) {
var state = $(tr).children("td").eq(i).html();
state = state.toLowerCase();
if (state.match(name)) {
suc = 1;
}
else if (suc !== 1) {
suc = 0;
}
}
if (suc === 1) {
$(tr).show();
}
else {
$(tr).hide();
}
});
$(table).trigger('update');
}
});
Table :
<table id='tableProject' class='tablesorter'>
<thead>
<tr>
<th>Project ID</th>
<th>Customer</th>
<th>Description</th>
<th>Status</th>
<th>Max Hours</th>
<th>Achieved</th>
<th>Difference</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
Upvotes: 0
Views: 91
Reputation: 40501
The .eq()
within the for loop could potentially (not positive) be the cause of your performance issues. Within each tr
you are saying "now iterate over the DOM multiple times and find td
with this index".
Also IMO, using a for loop within .each()
is redundant.
Avoid using .eq()
in this scenario and simply use .filter()
:
$(function () {
$("#searchValue").keyup(function () {
var table = $(this).siblings('table').not(':hidden'),
name = $("#searchValue").val().toLowerCase();
if (!name) {
$(table).find('tr').show();
$(table).trigger('update');
} else {
var trs = $(table).find('tbody tr');
trs.each(function () {
var tr = $(this),
results = null;
results = tr.find('td').filter(function () {
return $(this).html().toLowerCase().match(name);
});
if (!results.length) {
tr.hide()
} else {
tr.show();
}
});
$(table).trigger('update');
}
});
});
Upvotes: 1