检查是否使用 Javascript 选中复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5176264/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:57:11  来源:igfitidea点击:

Checking if a checkbox is checked with Javascript

javascriptcheckbox

提问by shinjuo

I have been trying to check if a checkbox is checked for awhile. For some reason it is not working correctly it just always says nothing is selected.

我一直在尝试检查复选框是否被选中了一段时间。由于某种原因,它无法正常工作,它总是说没有选择任何内容。

Function

功能

    if(document.theform.hail.Checked==true && document.theform.wind.Checked==false && document.theform.tornado.Checked==false){
        alert("Hail Checked");
}else{
        alert("Nothing Selected");
    }

Form

形式

<form name="theform" action="<?php echo $PHP_SELF; ?>" method="post">
      <div class="date">
        From: <script type="text/javascript">DateInput('orderdate', true, 'YYMMDD')</script>  To:<script type="text/javascript">DateInput('orderdatetwo', true, 'YYMMDD')</script>
      </div>
      <div class="checkBoxes">
        <input id="hail" name="hail" type="checkbox" value="hail">Hail<br />
        <input id="wind" name="wind" type="checkbox" value="wind">Wind<br />
        <input id="tornado" name="tornado" type="checkbox" value="tornado">Tornado<br />
        <input name="submit" type="submit" value="View Data" onClick="document.theform.action='<?php echo $PHP_SELF; ?>';">
        <input name="submit" type="button" value="Create KML" onClick="generatorChoice();">

回答by Matt Ball

The property should be in lowercase.

该属性应为小写。

var theform = document.theform;
if(theform.hail.checked && !theform.wind.checked && !theform.tornado.checked) {
    alert("Hail Checked");
} else {
    alert("Nothing Selected");
}

Also, as the above code shows:

另外,如上面的代码所示:

  • No need to check explicitly against trueor false
  • Store a reference to theformfor better performance
  • 无需明确检查truefalse
  • 存储引用以theform获得更好的性能

回答by Andrew Marshall

if(document.getElementById("hail").checked && !document.getElementById("wind").checked && !document.getElementById("tornado").checked) {
    alert("Hail Checked");
} else {
    alert("Nothing Selected");
}

回答by cHao

In Javascript, the property's called checked, not Checked.

在 Javascript 中,该属性称为checked,而不是Checked