2

Been looking lot but couldn't find, apply alternate row colors via jQuery on $(document).ready event.

$(document).ready(function(){  

    //Member Directory Table  
    $('.MemberDetail table tr:odd ').css('background','#F0F0EC');  
}  

colors applied, but when table is updated with ajax request, it doesn't update colors. So what could be the better way to apply alternate colors to that table?

There's an example on this page:

Here Dynamic Table

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user544892
  • 21
  • 1
  • 2

4 Answers4

5

You should use this script when Ajax is Complete. I mean something like

$.ajax({
  url: 'ajax/test.html',
  success: function(data) {
    //to do your jQuery code again;
    $('.MemberDetail table tr:odd ').css('background','#F0F0EC');
  }
});
Andrei Andrushkevich
  • 9,905
  • 4
  • 31
  • 42
1

you'll have to execute the table color function again, after the ajax request

function ajax() {
doAjaxStuff();

$('.MemberDetail table tr:odd ').css('background','#F0F0EC');
}
BenMorel
  • 34,448
  • 50
  • 182
  • 322
Ruben
  • 525
  • 6
  • 16
0

If you use a CSS class like this one for example:

.alternate
{
    background: #e6f4ff;
}

to apply an alternate color to table rows, it's easier... after doing some jQuery to add table rows dynamically, you can do something like this:

$("table tbody tr").removeClass("alternate").filter(":odd").addClass("alternate");

This should keep the rows colored correctly no matter what you do: be it adding or removing <table> rows.

Just remember you'll have to always run the code every time the <table> gets modified.

Leniel Maccaferri
  • 100,159
  • 46
  • 371
  • 480
0

Just update the table again:

$('.MemberDetail table').find('tr:odd').css('background','#F0F0EC').end().find('tr:even').css('background','#fff');

There's no magic way to automatically maintain those colours, just have to update each time you update the table.

brad
  • 31,987
  • 28
  • 102
  • 155