[英]How do I check if a checkbox is true in HTML and JavaScript?
我正在制作一张表格,检查您是否过敏。 这是我的基本表单,但是我需要检查是否已选中一个复选框。 我试过了,但是没有用。 各种杂物和文字都使用荷兰语,但您不必对此加以注意。 请帮助我检查是否已选中一个复选框。 谢谢!
<!doctype html>
<html>
<head>
<title>Selecteer allergieën</title>
<h1>Selecteer je allergieën hieronder</h1>
</head>
<body>
<form>
<label for="pinda">
<input type="checkbox" id="pinda" value="Pinda's">Pinda's
</label><br>
<input type="button" value="Gaan ->" onClick="myFunction()">
</form>
<script>
function myFunction(){
var pinda = document.getElementById("pinda").checked;
if(pinda = checked){
alert("Je bent allergisch voor pinda's");
}
}
</body>
</html>
剩下一个变量,因此您可以轻松查看代码。
你的问题是,你正在检查的输入是否被选中,它返回一个布尔值( true
/ false
),然后,在if
你分配一个未声明的变量的值checked
到变量pinda
。 您需要做的是:
function myFunction() { var pinda = document.getElementById("pinda").checked; if (pinda === true) { alert("Je bent allergisch voor pinda's"); } }
<form> <label for="pinda"> <input type="checkbox" id="pinda" value="Pinda's" />Pinda's </label> <input type="button" value="Gaan ->" onClick="myFunction()" /> </form>
或者,更简单地说:
function myFunction() { var pinda = document.getElementById("pinda").checked; if (pinda) { alert("Je bent allergisch voor pinda's"); } }
<form> <label for="pinda"> <input type="checkbox" id="pinda" value="Pinda's" />Pinda's </label> <input type="button" value="Gaan ->" onClick="myFunction()" /> </form>
顺便说一句,我建议将事件处理程序绑定在JavaScript中,而不是在HTML本身中绑定(这样可以实现不干扰JavaScript并更易于长期维护):
function myFunction() { var pinda = document.getElementById("pinda").checked; if (pinda === true) { alert("Je bent allergisch voor pinda's"); } } // using document.querySelector to retrieve the element from // the document that matches the supplied CSS selector: var button = document.querySelector('form input[type=button]'); // using addEventListener to bind myFunction as the // click event-handler for the button node: button.addEventListener('click', myFunction);
<form> <label for="pinda"> <input type="checkbox" id="pinda" value="Pinda's" />Pinda's </label> <input type="button" value="Gaan ->" /> </form>
</script>
那样结束。 if(pinda == true)
。 <!doctype html> <html> <head> <title>Selecteer allergieën</title> <h1>Selecteer je allergieën hieronder</h1> </head> <body> <form> <label for="pinda"> <input type="checkbox" id="pinda" value="Pinda's">Pinda's </label> <br> <input type="button" value="Gaan ->" onClick="myFunction()"> </form> <script> function myFunction() { var pinda = document.getElementById("pinda").checked; if (pinda === true) { alert("Je bent allergisch voor pinda's"); } } </script> </body> </html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.