tags:

views:

52

answers:

3

I'm using jquery ui sortable. When the rows are rearranged I want to reset the row colors to zebra striped. This is the code I'm using.

function reset_rows() {
 $("#rank tbody tr").removeClass("row1","row2");
 $("#rank tbody tr:even").addClass("row1");
}
$("#rank tbody").sortable({
 update : function() {
  reset_rows();
 }
});

The function adds the correct row colors then removes them all immediately. How can I get jquery to remove the row classes first then add back the row1 class to the even rows? It adds the row1 class first regardless of what order I use the functions in the code.

A: 

try using this syntax

$('rank tbody tr:even').addClass(function() {
          $("#rank tbody tr").removeClass("row1","row2");
          return "row1";
        });
In81Vad0
Remember that the function you pass to `addClass()` is being called on every `tr:even`. So if there are 20 of them, you're selecting *all* the `"#rank tbody tr"` from the DOM and calling `.removeClass()` 20 times, each time removing any previous `row1` that you returned. So only the last one will still have its `row1` class because the others have been removed several times over. Also, you're not calling `.removeClass()` correctly. It should be `.removeClass('one two')`.
patrick dw
+1  A: 

I wonder if there's something up with your CSS or some such, because basically that should work. I think I'd do it slightly differently, though:

$('tbody').sortable({
  update: function() {
    $('tr:odd').removeClass("even").addClass("odd");
    $('tr:even').removeClass("odd").addClass("even");
  }
});

(Obviously you'll want to contain those selectors a bit, I just did everything on my example page.)

Live example

You don't really need two classes (my apologies if I'm misreading this and you're not actually using two classes), you can just apply a class to (say) the even rows, which makes it simpler:

$('tbody').sortable({
  update: function() {
    $('tr:odd').removeClass("even");
    $('tr:even').addClass("even");
  }
});

Live example


Off-topic, but I assume you're doing this with JavaScript and classes because you have to support browsers that can't do this directly with CSS's nth-child pseudo class and such... (Sadly, IE6 is still a reality of life, isn't it? :-) )

T.J. Crowder
A: 

Thanks guys. I'm using the solution provided by T.J Crowder. It's simple and it works just fine. I actually had the problem before and I just ended up scrapping the zebra striping due to time constraints ( and frustration! ).

And yes I do need to support IE6. The application is being used on an intranet and IE6 is on every machine with no alternative...

JungAtHeart