Reputation: 2038
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>
Upvotes: 0
Views: 66
Reputation: 1208
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
}
}
Upvotes: 1
Reputation: 2486
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/
Upvotes: 3