Changing CSS visibility with JavaScript if a checkbox has been checked

前端 未结 2 1045
花落未央
花落未央 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:51

    First, in your HTML you have two elements. In JavaScript the easiest thing to do is get and save references to both.

    var box = document.getElementById('box');
    var checkbox = document.getElementById('check');
    

    Then you'll need to listen for changes to your checkbox. There is no 'checked' event, so you'll need to listen for any 'change'.

    // Put the 'event listener' on the 'check' element. 
    // It will run when the checkbox changes (is checked or unchecked)
    checkbox.addEventListener('change', function(){
        alert('changed');
    });
    

    Lastly within the event listener you can add more code to perform a check to see if the status of the checkbox is checked.

    checkbox.addEventListener('change', function(){
        alert('changed');
        // The checkbox element 'check' has a property 'checked' that you can access
        // If it is checked set the color one way, otherwise the other.
        if(checkbox.checked) {
            box.style.backgroundColor = 'red';
        } else {
            box.style.backgroundColor = 'lightblue';
        }
    });
    

    Here is a fiddle

    For further reading you could review the getElementById and EventListeners and the Style Object

    As a note about your javascript

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

    The code inside IF statement is correct. The IF statement itself tries to do too many things at once. You may have just forgotten one pair of closing parenthesis or put it in the wrong place. But you can also leave out the explicit check for 'true'. Try putting the code below within the event listener.

    if (document.getElementById("check").checked) {
        document.getElementById("box").style.visibility = "hidden";
    }
    

提交回复
热议问题