Javascript Form How to - Get CheckBox type








Question

We would like to know how to get CheckBox type.

Answer


<html>
    <form name="orderForm">
      <input type="checkbox" name="peppers">Peppers<br>
      <input type="checkbox" name="sausage">Sausage<br>
      <input type="checkbox" name="onion">Onion<br>
      <input type="checkbox" name="bacon">Bacon<hr>
      <input type="button" value="Order Pizza" name="orderButton" onClick="console.log('ordered.')">
    </form>
    <script language="JavaScript">
    var counter = 0;
    for(var x=0; x<document.orderForm.length; x++){
      if(document.orderForm.elements[x].type == "checkbox"){
        counter++;<!--  w  w  w . java2s  .  c  om-->
      }
    }
    document.write("Please select no more than 2 of the ");
    document.write(counter," possible toppings.");
    </script>
</html>

The code above is rendered as follows: