gpt4 book ai didi

javascript - 如何检查 HTML 和 JavaScript 中的复选框是否为真?

转载 作者:行者123 更新时间:2023-11-30 10:06:46 25 4
gpt4 key购买 nike

我正在制作一个表格来检查如果您过敏可以吃什么。这是我的基本形式,但我需要检查是否选中了复选框。我试过这个,但它不起作用。变量和文本是荷兰语,但您不必注意这一点。请帮我检查是否选中了复选框。谢谢!

 <!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>

剩下一个 var,所以你可以轻松地查看代码。

最佳答案

你遇到的问题是你正在检查输入是否被检查,它返回一个 bool 值(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 中绑定(bind)您的事件处理程序,而不是在 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>

关于javascript - 如何检查 HTML 和 JavaScript 中的复选框是否为真?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28657904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com