muffin muffin - 3 years ago 128
jQuery Question

Javascript Jquery - Change table cell colors upon checkbox click

I am creating a crossing matrix where I would cross entries; like male and female. I did this using a dynamically generated table where each cell pertains to a cross of a female.

Looks like this :

Female/Male | Male1 | Male2 |
------------------------------
Female1 | x | x |
------------------------------
Female2 | x | x |
-----------------------------


Above is a table, each cell contains a checkbox to identify the cross.

Below is the code i used to generate the table using php:

<table>
<?php
foreach($females...){
echo "<tr>";
...so on
//set up the rows and headers
foreach($males...){
echo "<td ...><input type='checkbox'../></td>
..and so on
}
}

?>
</table>


I need to color the cell like green or red, upon clicking the checkbox that is in it. How do I do this in Jquery/Javascript? and also, how do I ID each cell, and know the value (cross) it pertains to? If it is dynamic- the number of males and females are indefinite and changing so that the number of cells and checkboxes are also indefinite?

Answer Source

This assumes you want to do green when checked, red when not. You didn't exactly tell us which.

Find the parent of the checkbox. I do this with parents() always because if an element gets added to the stack later on, your code gets screwed up and you don't know why.

<td ...><input type='checkbox' 
         onclick="$(this).parents('td').css('background-color', $(this).is(':checked') ? 'green' : 'red');" />
</td>

Add in escaped quotes where necessary to get this to work with php's echo command.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download