1

I've been trying to figure this out for 2 days, but I couldn't find any solutions.

What I want is, every time I check the checkbox, an element's property will change(i.e. BGcolor of the body). but it only works when the checkbox is checked, but it doesn't work when the checkbox is unchecked.

var checkboxStatus = document.getElementById("menuCheckBox");
function menuToggle() {
    if (checkboxStatus.checked = true) {
        document.body.style.background = "cyan";
    } else {
        document.body.style.background = "magenta";
    }
}
menuToggle();
<input id="menuCheckBox" type="checkbox" onclick="menuToggle()"/>

3 Answers3

1

You're on the right track, just wrong use of operators. You used a single = instead of two. Boolean statements (comparison) needs two equals signs. https://www.guru99.com/difference-equality-strict-operator-javascript.html

var checkboxStatus = document.getElementById("menuCheckBox");
function menuToggle() {
    if (checkboxStatus.checked == true) {
        document.body.style.background = "cyan";
    } else {
        document.body.style.background = "magenta";
    }
}
menuToggle();
<input id="menuCheckBox" type="checkbox" onclick="menuToggle()"/>
You can also omit the == true entirely, as a true boolean statement is true itself without being compared to true.
atultw
  • 379
  • 2
  • 14
0

Problem: In this line

if (checkboxStatus.checked = true) {

Solution: There are 2 ways to resolve your problem:

  1. Make == instead like this: if (checkboxStatus.checked == true) {
  2. Remove = like this: if (checkboxStatus.checked) {

Explain:

  • = is the assignment operator. It sets a variable (the left-hand side) to a value (the right-hand side).
  • == is the comparison operator. It will tell you whether or not two values are equivalent regardless of the type of the operands.

Read more:

Refactor code:

var checkboxStatus = document.getElementById("menuCheckBox");
function menuToggle() {
    const backGroundCorlor = checkboxStatus.checked ? "cyan" : "magenta";
    document.body.style.background = backGroundCorlor;
}
menuToggle();
<input id="menuCheckBox" type="checkbox" onclick="menuToggle()"/>
Nguyễn Văn Phong
  • 11,572
  • 15
  • 21
  • 43
0

here you go

function colorchange() {
  if (document.getElementById('checker').checked) {
    document.body.style.backgroundColor = "orange";
  } else {
    document.body.style.backgroundColor = "grey";
  }
}
body {
  background-color: grey;
}
<input type="checkbox" onclick="colorchange();" id="checker"></input>
shoegazer
  • 48
  • 7