Javascript Form How to - Get selected CheckBox








Question

We would like to know how to get selected CheckBox.

Answer


<html>
    <script language="JavaScript">
    function submitOrder()<!--   ww  w. j a va  2  s .  c  o  m-->
    {
      var alertString = "Order: ";
      if(document.orderForm.lettuceCB.checked == true)
        alertString += " with lettuce ";      
      if(document.orderForm.cheeseCB.checked == true)
        alertString += "with cheese ";        
      if(document.orderForm.tomatoeCB.checked == true)
        alertString += "with tomatoe ";       
      console.log(alertString);
    }
    </script>
    <form name="orderForm">
      Lettuce
      <input type="checkbox" value="lettuce" name="lettuceCB"><br>
      Cheese 
      <input type="checkbox" value="cheese" name="cheeseCB"><br>
      Tomatoe
      <input type="checkbox" value="tomatoe"name="tomatoeCB"><hr>
      Step 2:
      <input type="button" value="Submit Order" name="orderButton" onClick="submitOrder()">
    </form>
</body>
</html>

The code above is rendered as follows: