Javascript: Processing radio buttons using for loop

In the earlier example, we have used many if else loops to process the radio buttons.

A more elegant way is to use for loop.

<!DOCTYPE html>
<html>
<head>
    <title>Form with radio buttons</title>
    <script>
        function submitForm(form) {

            var item;
            var i;
            var length;

            var radio_button = document.getElementsByName('radio_button');

            length = radio_button.length;

            for (i = 0; i < length; i++) {
                if (radio_button[i].checked) {
                    item = radio_button[i].value;
                    document.getElementById("buy_id").innerHTML = item;
                }
            }
        }
    </script>
</head>
<body>
<form>
    <p>What would you like to buy this year?</p>
    <input type="radio" name="radio_button" value="iPad" checked="checked">iPad<br>
    <input type="radio" name="radio_button" value="Camera">Camera<br>
    <input type="radio" name="radio_button" value="iPhone">iPhone<br>
    <input type="radio" name="radio_button" value="Car">Car<br>
    <input type="radio" name="radio_button" value="House">House<br>
    <input type="radio" name="radio_button" value="Aeroplane">Aeroplane<br>
    <input type="button" value="Submit" onclick="submitForm(this.form)">
</form>
<p>What I have bought</p>

<h3 id="buy_id"></h3>
</body>
</html>

 

The codes used in this example are a lot shorter and the number of lines needed in this for loop is almost equivalent to one if loop in the earlier example.

 

Series Navigation<< Javascript: Form with multiple radio buttons
Javascript: HTML DOM >>