Change Cell Colour Based on Checkbox

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
IGGt
Forum Contributor
Posts: 173
Joined: Thu Nov 26, 2009 9:22 am

Change Cell Colour Based on Checkbox

Post 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.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Re: Change Cell Colour Based on Checkbox

Post 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.
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
IGGt
Forum Contributor
Posts: 173
Joined: Thu Nov 26, 2009 9:22 am

Re: Change Cell Colour Based on Checkbox

Post by IGGt »

I see. I have removed the CellWhite as suggested, and modified the statement, and now it works.

cheers.
Post Reply