Skip to content Skip to sidebar Skip to footer

Javascript: Change Label Background Color On Checkbox

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 wo

Solution 1:

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)

Solution 2:

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

functionstatecheck(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/

Solution 3:

My solution based on your helpful input:

functionstatecheck(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/

Solution 4:

There are couple of mistakes, in your script.

  • You are passing lable id and checking for labelId.checked which does not exist
  • You are using = in if condition which should be ==

This is how you JS method should look like

functionstatecheck(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

<inputtype="checkbox" value="checkbox" onchange="statecheck('Alabama', this)" />

Solution 5:

You are missing an equals in the if statement.. Is that a typo error or is the solution to your problem?

Post a Comment for "Javascript: Change Label Background Color On Checkbox"