Javascript Form How to - Check and uncheck the CheckBox








Question

We would like to know how to check and uncheck the CheckBox.

Answer


<html>
    <form name="orderForm">
      <input type="checkbox" name="door4">4 doors<br>
      <input type="checkbox" name="door2">2 doors<hr>
      <input type="button" value="Submit Order" name="orderButton" onClick="submitOrder()">
    </form>
    <script language="JavaScript">
    function submitOrder() {<!--from w  w w .  j av  a  2 s . c o  m-->
      if((document.orderForm.door4.checked == true) && (document.orderForm.door2.checked == true)){
        console.log("You selected two different door styles. Reselect door style.");
        document.orderForm.door4.checked = false;
        document.orderForm.door2.checked = false;

      }else if((document.orderForm.door4.checked == false) && (document.orderForm.door2.checked == false)){
        console.log("You did not select a door style! Please select a door style.");
      } else  {
        var alertString = String("Order: ");
        if(document.orderForm.door4.checked == true)
          alertString += "4 doors.";       
        if(document.orderForm.door2.checked == true)
          alertString += "2 doors.";       
        console.log(alertString);
      }
    }
    </script>
</html>

The code above is rendered as follows: