开发者

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; ?开发者_JAVA百科>" 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");
}


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜