Jack Hillard Jack Hillard - 1 year ago 135
jQuery Question

Show/hide table row if specific cell is empty

I have several tables on a page with various id's. I have a checkbox on the page and whenever the checkbox is checked I'd like every single row (in all tables) with an empty td 4 to hide. When the checkbox is unchecked I'd like to show all rows again.

I've searched around Stack Overflow and I've got some code (just trying to hide so far) but I can't get it to work.

$("#checkbox").change(function() {
$("table tr").each(function() {
var cell = $.trim($(this).find("td:eq(4)").text());
if (cell.length == 0) {
$(this).addClass("nodisplay");
}
});
});


Edit: here is a jsfiddle - http://jsfiddle.net/6bfjw/

Answer Source

You were just close.

I have implemented only hide part as question has done. You can do the rest.

PROBLEM: Selecting heading or th as well.

SOLUTION: Select using tbody.

Your working code should go like this:

$("#checkbox").change(function(){
    $("table tbody tr").each(function() {        
        var cell = $.trim($(this).find("td:eq(4)").text());
        if (cell.length == 0){
            console.log("empty");
            $(this).addClass("nodisplay");
        }                   
    });
});

DEMO

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download