LCJ
LCJ

Reputation: 22652

Select table cells based on the value in the cell

I have a table as shown in http://jsfiddle.net/Lijo/UqdQp/4/. I need to set background color as red for all columns that has value “1”. What is the best way (in terms of performance) for doing this using jQuery?

Note: After doing the background color, I need to alert the value of the table cell also. That means I need to use “this” operator on the selected cell.

Reference Answers:

  1. http://jsfiddle.net/Lijo/uGKHB/11/
  2. http://jsfiddle.net/Lijo/uGKHB/12/
  3. Finding column index using jQuery when table contains column-spanning cells

Upvotes: 0

Views: 1347

Answers (2)

saji89
saji89

Reputation: 2251

I have used the each function of jQuery to iterate over each table cells and highlight the cell when it matches the required condition.
Working demo: http://jsfiddle.net/saji89/uGKHB/

$('.resultGridTable td').each(function()
{
    if($(this).html()==1)
    {
        $(this).css({'background':'#FF0000'});
    }        
});

Using contains selector instead of if conditional, should be more faster: http://jsfiddle.net/saji89/WbXTr/

Upvotes: 1

chovy
chovy

Reputation: 75666

var $tds = $("td").filter(function(i){
    return $(this).html() == 1;
});

$tds.css({ background: 'red' });

$.each($tds, function(i, x){
    console.log($(x).html());
});

I used console.log instead of alert for obvious reasons.

Upvotes: 1

Related Questions