Skip to content Skip to sidebar Skip to footer

How To Hide A Table Row Depending On A Value In One Of Its Column

I have a table like the following. <

Solution 1:

Assuming your erledigt column is always the second last column then it should be very straight forward.

Iterate through the rows and not the cells and find the second last cell in each row and show/hide the row as required.

$('#subtask_table tr').each(function() {
    var$erledigtCell = $(this).find("td").last().prev();
    var$row = $erledigtCell.parent();

    if($erledigtCell.text() == '1'){
        $row.hide();
    } else {
        $row.show();
    }
});

If you have any influence on how the grid is generated it would be much better if you can add a custom attribute to the tr, for example data-erledigt=.... Than you have no traversing to do and it doesn't matter which column erledigt is displayed in.

With Html like this:

<trdata-erledigt=0>....
.....
<trdata-erledigt=1>

You could write a jQuery as simple as:

$("tr[data-erledigt='0']").hide();

Solution 2:

$('#subtask_table tr td:eq(6)').each(function() { // eq(6) selects the 7-th td, which is the "completed" columnif(this.innerHTML === '0' || this.innerHTML === '')
    {
        $(this).parent().hide(); // td.parent returns the tr
    }
});

Also, this is redundant (though I'm not sure what this accomplishes, maybe you want to show the rows (tr not td) instead):

$('#subtask_table td').each(function() {
    $(this).show();
});

Simply use:

$('#subtask_table td').show();

Solution 3:

I'd probably do this:

$(document).ready(function() {
    $('#cbHideCompleted').click(function() {
        if($(this).prop('checked')) {    
            $('#subtask_table td:nth-child(7)').each(function() {
                //if td is 'completed' columnvar val = $(this).text();
                if (val === "" || val === "0")
                    $(this).parent().hide();    
            });
        } else {
            $('#subtask_table tr').show();
        }
    });
});

The :nth-child() selector "Selects all elements that are the nth-child of their parent", so $('#subtask_table td:nth-child(7)') selects all the td elements in the 7th column. So loop through those cells and if the text content is an empty string or "0" hide its parent tr element.

In your else branch you don't need an .each() loop: you can call .show() directly on a jQuery object that contains multiple elements and all the elements will be shown.

Post a Comment for "How To Hide A Table Row Depending On A Value In One Of Its Column"

IDTitel