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

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>

还剩一个var,方便你查看代码。

您遇到的问题是您正在检查输入是否被检查,returns 一个布尔值 (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. 如果现在条件也合适应该是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>