Form handling onsubmit, onchange, onselect, onblur, onfocus

2. onsubmit

2.1. Retrieving the values from checkboxes using value and onsubmit

          The code snippet below shows another example of using onsubmit and value to retrieve values from the user for processing in the JavaScript code. This example uses a set of checkbox options that have the same name. The JavaScript code retrieves all options using getElementsByName() and loops through all options in the checkbox set and checks each option if they are checked. When the item is checked, it is added to a string to be alerted.

 <form onsubmit="return myFunction();">

    <h2> Add-ons for my milktea </h2>

    <input type="checkbox" id="creamCheese" name="choices" value="Cream Cheese">

    <label for="creamCheese"> Cream Cheese</label><br>

    <input type="checkbox" id="pearls" name="choices" value="Pearls">

    <label for="pearls"> Pearls </label><br>

    <input type="checkbox" id="coffeeJelly" name="choices" value="Coffee Jelly">

    <label for="coffeeJelly"> Coffee Jelly</label><br><br>

    <input type="submit"></input>

</form>

<script>

    function myFunction(){

        var x ="";

        var choices = document.getElementsByName("choices");

        for (var i=0; i<choices.length; i++){

            if (choices[i].checked){

                x = x + choices[i].value + " ";

            }

        }

        alert("You have chosen " + x);

        return false;

    }

</script>