0

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
Community
  • 1
  • 1
LCJ
  • 22,196
  • 67
  • 260
  • 418
  • All columns that contain *a* 1, or all columns for which all contained values (with the exception of the header row) *are* 1? – David Thomas Sep 18 '12 at 07:25

2 Answers2

1

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/

saji89
  • 2,093
  • 4
  • 27
  • 49
1
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.

chovy
  • 72,281
  • 52
  • 227
  • 295
  • It does coloring for "1234" also. How can we overcome this? http://jsfiddle.net/Lijo/uGKHB/3/ – LCJ Sep 18 '12 at 06:57
  • Thanks. I tried to apply this to header cell - did not work. Any idea why? http://jsfiddle.net/Lijo/uGKHB/7/ – LCJ Sep 18 '12 at 07:17
  • 1
    `return $.trim($(this).html()) == 'Type';` -- you have to trim the whitespace out. http://jsfiddle.net/uGKHB/9/ – chovy Sep 18 '12 at 07:22
  • Thanks. Answers are available in http://jsfiddle.net/Lijo/uGKHB/11/ and http://jsfiddle.net/Lijo/uGKHB/10/ – LCJ Sep 18 '12 at 07:27