简体   繁体   English

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

[英]Checking if a checkbox is checked with Javascript

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();">

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 true or false 无需明确检查truefalse
  • Store a reference to theform for better performance 存储对theform的引用以获得更好的性能
if(document.getElementById("hail").checked && !document.getElementById("wind").checked && !document.getElementById("tornado").checked) {
    alert("Hail Checked");
} else {
    alert("Nothing Selected");
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM