Reputation: 339
I want to search in a table. i copied a workin JS from a tutorial site. it worked perfectly
to see the original working configuration -> http://jsfiddle.net/9T9CZ/4/
just type something in the text box, eg Flower, if you want to search for flower.
After my modification, which was adding a new <tr>
with a <div>
inside, the search stopped working.
mod.Fiddle Version: http://jsfiddle.net/9T9CZ/5/
Firebug breaks if you type any letter in the search-box with: targetTable.rows.item(...).cells.item(...) is null
I belive this problem is the emty div in the new <tr>
Does anyone has an idea to correct this or to work around?
Upvotes: 0
Views: 86
Reputation: 23406
You're close, adding a colspan
breaks your code. Instead of detecting only the amount of the cells in the first row, you need to check each row.
The snippet below does the trick. I've also simplified your code a bit.
function doSearch() {
var searchText = document.getElementById('searchTerm').value.toLowerCase(),
table = document.getElementById('dataTable'),
text = (document.body.textContent) ? 'textContent' : 'innerText', // Feature detection
rows = table.rows, // Caching rows
rLen = rows.length,
r, rowText, cells, cols, c;
for (r = 1; r < rLen; r++) { // Ignoring the first row
if (rows[r].className.indexOf('some_classname') < 0) {continue;} // className check
rowText = '';
cells = rows[r].cells; // Caching the cells
cols = cells.length;
for (c = 0; c < cols; c++) {
rowText += cells[c][text];
}
rowText = rowText.toLowerCase();
if (rowText.indexOf(searchText) < 0) {
table.rows[r].style.display = 'none';
} else {
table.rows[r].style.display = 'table-row';
}
}
}
innerText
/textContent
instead of browser detection.thead
starting the r
-loop from 1
(the only permitted direct content of thead
is tr
).rows
and .cells
collections makes the code fasterUpvotes: 1