Javascript: Processing radio buttons using for loop

This entry is part 22 of 27 in the series Javascript Tutorial

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>
    <title>Form with radio buttons</title>
        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;
    <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)">
<p>What I have bought</p>

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


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 >>