Click here to Skip to main content
14,836,727 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
i want to set background color to a table ,
i have written something like this in my code

table id is: datatable

$('tr').each(function () {
if ($(this).find('td').eq(4).text().trim() === "yes") {
$(this).css('background', 'green');
}

});

it is working fine, but problem is color is applying to alternation rows values, i mean suppose if two rows contains text value "yes" it is applying to only second row value not to the first one, like this is applying ,but i need to set the color to the rows where ever text value contains "yes", please help me how to solve this?

Note:All data is coming dynamically!!!!!!!!!!
Posted
Updated 15-Sep-14 18:25pm
v3
Comments
Snesh Prajapati 15-Sep-14 2:20am
   
On click of any column in table, you want to get the value of last column?

You can use a ternary operator to assign check text and assign color value as follows.

C#
$('tr').each(function () {
var cell =$(this).find('td').eq(4);
var color=cell.text().trim() == "yes"?"Green":"Red";
cell.css('background', color);
}
});



Let me know if this helps.

Regards,
Adil Shaikh
   
Comments
pavan_ kumar 15-Sep-14 23:47pm
   
thanks, it is working fine
Change td:last to td:eq(wanted_index)[^] - read jQuery documentation in the link.

Depending on what you mean by data is coming dynamically (that is, if wanted column changes position) you'll have to mark it some way - adding class, adding new field in your data which return exact index etc... Otherwise just use fixed index in eq function
   
v2
Comments
pavan_ kumar 15-Sep-14 23:46pm
   
thanks
pavan_ kumar 16-Sep-14 0:22am
   
i have tried this way, it is working fine, but color is applying only to alternation rows i mean suppose two lines immediately contains text "yes" it is getting applying to only second row value not to the first one, why like this? how can i solve this?
Sinisa Hajnal 16-Sep-14 2:06am
   
This is matter of row selection.

You have different selectors for odd and even rows. You're applying this change to both, but later it is overwritten by a rule for different background in every other row. Check excellent Chrome Developer tools or Firebug for Firefox, both can show you the rules applied to an element.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900