Changing CSS visibility with JavaScript if a checkbox has been checked

前端 未结 2 1061
花落未央
花落未央 2021-01-25 18:09

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.

2条回答
  •  我在风中等你
    2021-01-25 18:58

    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:

    
    

    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.

提交回复
热议问题