I am trying to change the background color of a label in each checkbox in a form based on the checked/unchecked state of the checkbox.So far I got it to change initially, but it
Your are not setting the color on the label but on the checkbox. jQuery makes it easy for you to select / traverse DOM elements (and also helps clean-up a lot of unnecessary IDs), see this fiddle :
http://jsfiddle.net/7wnCL/17/
$('input[type=checkbox]').change(function(){
if($(this).prop('checked')){
$(this).parent().css('backgroundColor', '#bff0a1');
}else{
$(this).parent().css('backgroundColor', '#eee');
}
});
There are couple of mistakes, in your script.
This is how you JS method should look like
function statecheck(layer, checkbox) {
var myLayer = document.getElementById(layer);
//myLayer.style.backgroundColor = "#bff0a1";
if(checkbox.checked == true){
myLayer.style.backgroundColor = "#bff0a1";
} else {
myLayer.style.backgroundColor = "#eee";
};
}
HTML
<input type="checkbox" value="checkbox" onchange="statecheck('Alabama', this)" />
You are missing an equals in the if statement.. Is that a typo error or is the solution to your problem?
the non-jQuery route. pass a second param to your statecheck function.
<label title="American Samoa" id="AmericanSamoa"><input type="checkbox" value="checkbox" onchange="statecheck(this,'AmericanSamoa')" />AS</label>
and the javascript
function statecheck(chk, layer) {
var myLayer = document.getElementById(layer);
//myLayer.style.backgroundColor = "#bff0a1";
if(chk.checked === true){
myLayer.style.backgroundColor = "#bff0a1";
} else {
myLayer.style.backgroundColor = "#eee";
}
}
http://jsfiddle.net/7wnCL/4/
http://jsfiddle.net/7wnCL/20/
myLayer.checked = true
is an assignment, not a condition.
if (myLayer.checked = true)
is every time evaluated as
if (true)
And the else part will never be executed. So change it to:
if (myLayer.checked === true)
Also, you should check for the input, and not for the layer, which doesn't have any checked property:
if (myLayer.childNodes[0].checked === true)
My solution based on your helpful input:
function statecheck(layer) {
var myLayer = document.getElementById(layer);
//myLayer.style.backgroundColor = "#bff0a1";
if(myLayer.childNodes[0].checked === true){
myLayer.style.backgroundColor = "#bff0a1";
} else {
myLayer.style.backgroundColor = "#eee";
};
}
http://jsfiddle.net/7wnCL/29/