HKK
HKK

Reputation: 339

JS-Search function fails

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

Answers (1)

Teemu
Teemu

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';
        }
    }
}
  • Feature detection for innerText/textContent instead of browser detection.
  • Ignoring the thead starting the r-loop from 1 (the only permitted direct content of thead is tr)
  • Caching .rows and .cells collections makes the code faster

A live demo at jsFiddle.

Upvotes: 1

Related Questions