简体   繁体   中英

How can I add/remove an html element depending on a checkbox being selected with only javascript?

I would like an html to appear only when a checkbox in a form is selected. How can I do this with only javascript?

<html>
<head><title>test</title></head>
<body>
  <form>
    <input type="checkbox" id="exampleCheckbox">
  </form>
  <div id="toggleElement"></div>
</body>
</html>

Edit: What I have tried, but it does not disappear after being unselected:

<html>
<head><title>test</title></head>
<body>
  <form>
    <input type="checkbox" id="exampleCheckbox" onclick="showDiv()">
  </form>
  <div id="toggleElement"></div>
  <script>
  function showDiv() {
    document.getElementById("toggleElement").innerHTML = "Hello world!";
  }
  </script>
</body>
</html>

You can do it using eventlistener:

document.getElementById("checkbox").addEventListener('change',function() {
        var hidden = document.getElementById("html");
        if (this.checked) {
            hidden.style.display = "block";
        } else {
            hidden.style.display = "none";
        }
    })

http://jsfiddle.net/j7wdkd7a/3/

You can add an onchange event to the checkbox, like this:

<input type="checkbox" id="exampleCheckbox" onchange="myFunction()">

So myFunction will be called when the checkbox changes.

Then in your script:

function myFunction()
{
    // First check the state of the checkbox:
    if (document.getELementById("exampleCheckbox").checked) {
        // if it is checked, show the element:
        document.getElementById("toggleElement").style.visibility = "visible"; // make the div visible
    } else {
        // the checkbox is unchecked
        document.getElementById("toggleElement").style.visibility = "hidden"; // make the div invisible
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM