views:

502

answers:

3

I am successfully using jquery odd/even selectors to create a "tiger striping" on a table. Then I added ability to add or deleted rows. However I have not been able to get striping to work properly on add/delete of row. It works for a an add/append, but not on add/prepend or delete. Here is summary of the code...

$(document).ready(function(){

    // click on Add Row button
    $("#addButton").click(function(){
        // add a row to table 
        addTableRow('#myTable');                   
        // then re-apply tiger striping
         stripeRows();
    });
}); 


// remove specified row
function removeRow(row) {
    $(row).parent("tr").remove();
    stripeRows();
}


function StripeRows()
{
    $("#myTable").each(function(){
        $(this).find("tr:even").addClass("evenrow");
        $(this).find("tr:odd").addClass("oddrow");
    });
}
A: 

You need to clear your previous striping first:

function StripeRows()
{
    $("#myTable").each(function(){
        $(this).find("tr").removeClass('evenrow oddrow');
        $(this).find("tr:even").addClass("evenrow");
        $(this).find("tr:odd").addClass("oddrow");
    });
}

Otherwise you'll end up with rows that have both evenrow and oddrow classes.

Tatu Ulmanen
+3  A: 

It's not working probably because you're not removing the old class.

I have two pieces of advice:

  1. Don't use :even and :odd. These typically don't behave how you'd expect. Instead use :nth-child(even) and :nth-child(odd) respectively; and
  2. Don't have both even and odd classes. You don't need them both. Just use an odd (or even) class and have the style for the table cover the other case.

So you should do something like this:

function StripeRows() {
  $("#mytable > tbody > tr").removeClass("oddrow")
    .filter(":nth-child(odd)").addClass("oddrow");
}

This function removes the "oddrow" classes from all rows in the table and then adds the "oddrow" class to the odd rows in the table.

If you still want the oddrow/evenrow (which imho just adds extra unnecessary code), it's not much of a change:

function StripeRows() {
  $("#mytable > tbody > tr").removeClass("oddrow evenrow")
    .filter(":nth-child(odd)").addClass("oddrow")
    .end().filter(":nth-child(even)").addClass("evenrow");
}
cletus
brilliant! thanks.
rshid
A: 

Perhaps you should try this first?

$(this).find("tr").removeClass();
Paul Creasey