3

Been Googling this for over an hour, and getting answers to much more complex questions but not this simple one, and my Dummies book is no help.

I want to change the background of a row if a particular cell has a value. So:

$('#MyTable tr').each (function(index) {

    $(this).css('background-color', '#FCDCE4');

});

Works fine to change the bg color in every row, but how can I do this only in rows where column 30 has a value? I could probably give my target cell a css class and do it that way, but I'd really rather learn to use jQuery properly (so that I don't need to keep posting elementary questions).

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Stanton
  • 1,334
  • 4
  • 18
  • 32
  • possible duplicate of [How to get a table cell value using jquery?](http://stackoverflow.com/questions/376081/how-to-get-a-table-cell-value-using-jquery) – p.campbell Feb 15 '12 at 14:35
  • 1
    As a general point: have you tried just reading the official documentation, rather than trying to google this? – Marcin Feb 15 '12 at 14:36
  • Yes. Thanks for your contribution. – Stanton Feb 15 '12 at 17:54

3 Answers3

5

Description

You can use jQuery .children() and .eq() to get the cell 30.

Note that .eq() is zero based, so you need to use 29 to get the 30th cell

Sample

$('#MyTable tr)').each (function(index) {
    var cell = $(this).children("td").eq(29)

    // your if condition

    $(this).css('background-color', '#FCDCE4');
});

More Information

Community
  • 1
  • 1
dknaack
  • 60,192
  • 27
  • 155
  • 202
  • Thank you, and I'll look at those links that you supplied - although some of that documentation is still a bit above me, I'm afraid. – Stanton Feb 15 '12 at 18:07
3
$('table td:nth-child(30):empty').each(function(){
  $(this).css('background-color','#FCDCE4'); // empty column
});

nth-child selector to grab the 30th column :empty to grab empty cells.

Example on jsFiddle can be found here: http://jsfiddle.net/pYA4U/

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
1

First, put the reference to the table inside a variable:

var table = $( '#myTable' )[0];

You probably want to keep this reference available throughout your application (so that all your methods have access to it).

Next:

var nr = 30; // the column number

$( table.rows ).each( function () {    
    if ( $( this.cells ).eq( nr - 1 ).text() ) {
        $( this ).addClass( 'selected' );
    }
});

So, if the 30. cell has any text-content, add the 'selected' class to the row.

Live demo: http://jsfiddle.net/2C6C7/

Šime Vidas
  • 182,163
  • 62
  • 281
  • 385