Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate row colors when you have rowspan

Tags:

html

jquery

I have this HTML:

<table class="altRowTable">

<script type="text/javascript">
  $(document).ready(function() {
    $("table.altRow tr:odd").css("background-color", "#DEDFDE");
  });
</script>

This works fine until I have some rows that contains a rowspan (it's not consistent across the rows).

So I have something like this (below "-" represents a space - can't really do tables in SOF :) )

|---ID---|---name---|---Number---|   
|---1----|---joe----|-----1------|   
|--------|---tom----|-----2------|   
|---2----|---joe----|-----3------|   
|---3----|---joe----|-----4------|   
|---4----|---joe----|-----6------|   
|---5----|---joe----|-----5------|   
|--------|---tom----|-----3------|   

How can i keep all the rows within the rowspan the same backcolor ?

like image 249
leora Avatar asked Feb 03 '23 03:02

leora


1 Answers

There may be a slicker way to do it, but here's one way:

$("table.altRow tr").filter(function() { 
  return $(this).children().length == 3;
}).filter(':even').addClass('alt'​​​​​​);

$("tr.alt td[rowspan]").each(function() {
  $(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('alt');
});

This uses a CSS class instead of the color, like this:

.alt { background-color​: #DEDFDE; }​

You can give it a try here, you can swap :even and :odd in the first code block to do whichever pattern you want (with the example, :odd doesn't illustrate it well, since that's the rows without rowspan cells).

What this does is find the rows with all the cells, not partial rows, gets the odd or even ones of those and applies a class. Then the second pass looks at those rows, and if they have any rowspan="" cells it gets that .rowSpan (DOM property), minus one for the current row, and applies the class that many rows down, via .nextAll() and .slice().

like image 171
Nick Craver Avatar answered Feb 06 '23 06:02

Nick Craver