Search code examples
javascriptcsscheckboxchecked

Changing CSS visibility with JavaScript if a checkbox has been checked


In the snippet below, blue div should hide when the checkbox is checked. Yet, it doesn't. I've tried a lot of different syntax, but no luck so far.

if (document.getElementById("check".checked = "true")) {
      document.getElementById("box").style.visibility = "hidden";
}
#box {
      background: lightblue;
      width: 200px;
      height: 200px;
}
<input type="checkbox" id="check">
<div id="box"></div>


Solution

  • Here is what you wanted. http://jsfiddle.net/3ywqy72w/8/

    There were many problems with the code you have placed above.

    In the HTML, you need to call a function for javascript to do something once the checkbox is clicked. That looks like this:

    <input type="checkbox" id="check" onclick="toggleBoxVisibility()">
    

    In the Javascript, you also did not create the function that will be used to make code happen once the onClick is called. This is what that looks like:

    function toggleBoxVisibility() {
    
    if (document.getElementById("check").checked == true) {
    
        document.getElementById("box").style.visibility = "visible";
    
        } 
    else {
    
        document.getElementById("box").style.visibility = "hidden";
    
        }
    }
    

    Note some of the syntax. In your code, there was only one "=" which sets a value. This will do nothing in an if statement. To compare values, you must use two as shown above.

    Lastly, you were only checking once to see if the checkbox was checked and not the other way around. That would only work once and would never display the opposite case.