Page 1 of 1

Change Cell Colour Based on Checkbox

Posted: Fri Jul 13, 2012 8:10 am
by IGGt
I have a table set up which contains a set of checkboxes, and am looking for a way to change the background colour of the cell, based on whether the checkbox is checked or not.

I have got as far as:

Code: Select all

<!--THE TABLE -->
<form name="DBReturn" action="#" method="post">
<table id="DBSelectIgnTable" class="DBSelectTable">
<tr>
<td class="CellWhite "><INPUT TYPE="checkbox" NAME="ignore[]" VALUE="1"></td>
<td class="CellWhite "><INPUT TYPE="checkbox" NAME="ignore[]" VALUE="2"></td>
<td class="CellWhite "><INPUT TYPE="checkbox" NAME="ignore[]" VALUE="3"></td>
<td class="CellWhite "><INPUT TYPE="checkbox" NAME="ignore[]" VALUE="4"></td>
</tr>
</table>

<p class="submitRed">
<input type="submit" Name="submit" value="Ignore These Databases">
</p>
</form>

Code: Select all

<!--THE JAVASCRIPT-->
<script type="text/javascript">

$(document).ready(function()
{
    $("#DBSelectIgnTable td :checkbox").click(function()
		{ 
    		if (this.checked) 
    			{
       				$(this).addClass('CellRed');
    			}
    			else
    			{
       				$(this).addClass('CellWhite');
    			}
		}
		)
}
);
</script>
however, it currently doesn't work. Can someone point out where I am going wrong please.

Re: Change Cell Colour Based on Checkbox

Posted: Fri Jul 13, 2012 10:22 am
by pickle
You my need to remove the opposite class.

However, it may be easiest to just remove the "CellWhite" class entirely, and make the table cells white by default. Then, just add or remove the "CellRed" class as necessary.

Have you checked to see if your selector is even working?
If you're using the latest version of jQuery, the new way of attaching events would be something like this:

Code: Select all

$("#DBSelectIgnTable").on('click','input:checkbox',function().....
This would allow you to only attach 1 listener to the DOM, rather than 1 for every checkbox. The code inside the function could behave the same though.

Re: Change Cell Colour Based on Checkbox

Posted: Fri Jul 13, 2012 10:40 am
by IGGt
I see. I have removed the CellWhite as suggested, and modified the statement, and now it works.

cheers.