简体   繁体   中英

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
  • Store a reference to theform for better performance
if(document.getElementById("hail").checked && !document.getElementById("wind").checked && !document.getElementById("tornado").checked) {
    alert("Hail Checked");
} else {
    alert("Nothing Selected");
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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