Javascript Form How to - Get CheckBox name








Question

We would like to know how to get CheckBox name.

Answer


<html>
    <form name="orderForm">
      <input type="checkbox" name="V6">V6<br>
      <input type="checkbox" name="V8">V8<hr>
      <input type="button" value="Submit Order" name="orderButton" onClick="submitOrder()">
    </form>
    <script language="JavaScript">
    function submitOrder()<!--   w  w  w .  ja  v a  2 s  .co  m-->
    {
      var alertString = String("You have selected a ");

      if(document.orderForm.V6.checked == true)
        alertString += document.orderForm.V6.name;  
      else
        alertString += document.orderForm.V8.name;  
      alertString += " truck.";
      console.log(alertString);
    }
    </script>
</html>

The code above is rendered as follows: