[英]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. 我希望仅在选中表单中的复选框时才会显示html。 How can I do this with only javascript?
我该如何仅使用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: 您可以使用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/ http://jsfiddle.net/j7wdkd7a/3/
You can add an onchange
event to the checkbox, like this: 您可以将
onchange
事件添加到复选框,如下所示:
<input type="checkbox" id="exampleCheckbox" onchange="myFunction()">
So myFunction
will be called when the checkbox changes. 因此,当复选框更改时,将调用
myFunction
。
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.