Javascript Form How to - Handle click event on CheckBox








Question

We would like to know how to handle click event on CheckBox.

Answer


<html>
    <form name="orderForm">
      <input type="checkbox" name="peppers" onClick="recommendSausage()">Peppers<br>
      <input type="checkbox" name="sausage">Sausage<hr>
      Step 2:<!--  w w w. ja va 2 s . c om-->
      <input type="button" value="Order Pizza" name="orderButton" onClick="console.log('ordered.')">
    </form>
    <script language="JavaScript">
    function recommendSausage()
    {
      if(document.orderForm.peppers.checked == true)
      {
        console.log("Sausage goes well with peppers.");
      }
    }
    document.write("The pepper checkbox onClick event handler: ");
    document.write(document.orderForm.peppers.onclick);
    </script>
</html>

The code above is rendered as follows: