如何在HTML和JavaScript中检查复选框是否为真

How do I check if a checkbox is true in HTML and JavaScript?

本文关键字:复选框 检查 是否 JavaScript HTML      更新时间:2024-02-27

我正在制作一份表格,检查如果你过敏,可以吃什么。这是我的基本表单,但我需要检查是否选中了复选框。我试过了,但没用。变体和文本都是荷兰语,但你不必注意这一点。请帮我检查是否选中了复选框。非常感谢。

 <!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,因此您可以轻松地查看代码。

您面临的问题是,您要检查输入是否已检查,这将返回布尔值(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>

  1. 现在我知道你的问题标签需要像</script>一样结束
  2. 如果条件现在也是正确的,则应该是CCD_ 7

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