Tiger Tiger - 6 months ago 18
jQuery Question

Table: Check all rows, then check all tds with class, take action

banging my head against the wall on this. I'm trying to clear table if all rows

tr
and columns
td
contain the text "null". Right now it looks for if only one row (first row) contains null, not all rows combined. Problem: what if one row contains null but others don't, in that case I don't want to clear my table.

Also reason I have the filter function set is so I can check all
td
s within that row, not just one
td
. Trying to do same thing with the rows, I tried setting a variable and using the same code but for
tr
s but that didn't work either.

The way I have it setup now; 1. select first row, 2. find all tds with .tocheck (Looking for tds with class because I don't want to search certain tds). 3. Then add class .allare. 4. Now if the .allare class exists, clear table (DataTables).

$('.mytable>tbody>tr:first').filter( function(){
return $(this).find('td.tocheck').length == $(this).find('td.tocheck:contains("null")').length;
}).addClass('allare');
if ($(".allare")[0]){
var oTable = $('.mytable').dataTable();
oTable.fnClearTable();
}


Only reason I'm checking for first row is because I had issues checking for all rows not just one. What I'm trying to do it search all rows, not just one or the first. Any thoughts on how to search all rows with the other checks I already have?

Answer

Try this http://jsfiddle.net/aamir/S6hc6/

This will check all tables and all its <td> to see if all have the text null.

Following modified to match your code

$('table').each(function(){
    var numberofnull = 0, 
        table = $(this);

    table.find('td').each(function(){
        if( $.trim( $(this).text() ) === "null" ) numberofnull++;
    });

    if(numberofnull != table.find('td').length) {
        table.dataTable().fnClearTable();
    }
});