Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
184
rated 0 times [  187] [ 3]  / answers: 1 / hits: 68347  / 11 Years ago, sun, october 27, 2013, 12:00:00

For example:
You have a table, and it has 4 tds and 2 trs. Table's background color is white. If i click to A td, A td should be red, than if i click to B, B td should be red and A td should be red too. If i click to C than, C should be red and B and A should be red too.



I have something like this. But it isnt good, because when i click again i want to change color back to white.



http://jsfiddle.net/k8UgT/193/



The code i use



<table>
<tr>
<td onclick=function()>AAA</td>
<td onclick=function()>BBB</td>
<td onclick=function()>CCC</td>
</tr>
<tr>
<td onclick=function()>DDD</td>
<td onclick=function()>EEE</td>
<td onclick=function()>FFF</td>
</tr>
</table>


JS:



$( function() {
$('td').click( function() {
$(this).css('background', '#aaa')
} );
} );

More From » jquery

 Answers
4

Welcome to SO.



First of all you don't need to onclick attribute on the td's. Second of all I would suggest using a CSS class instead of setting the background color.



CSS



.red-cell {
background: #F00; /* Or some other color */
}


JS



$( function() {
$('td').click( function() {
$(this).toggleClass(red-cell);
} );
} );


Read more about toggleClass here.
Updated fiddle


[#74705] Friday, October 25, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luizc

Total Points: 623
Total Questions: 87
Total Answers: 103

Location: Zimbabwe
Member since Sat, Feb 27, 2021
3 Years ago
;