Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();">
like image 803
shinjuo Avatar asked Jun 12 '26 14:06

shinjuo


2 Answers

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
like image 92
Matt Ball Avatar answered Jun 15 '26 03:06

Matt Ball


if(document.getElementById("hail").checked && !document.getElementById("wind").checked && !document.getElementById("tornado").checked) {
    alert("Hail Checked");
} else {
    alert("Nothing Selected");
}
like image 35
Andrew Marshall Avatar answered Jun 15 '26 05:06

Andrew Marshall



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!