Javascript: Form with multiple radio buttons

We first look at a form with multiple radio buttons and see how we could use simple if loops to access the buttons.

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

            var item;
            var i = 0;

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

            if (radio_button[i].checked) {
                item = radio_button[i].value;
                document.getElementById("buy_id").innerHTML = item;
            } else if (radio_button[++i].checked) {
                item = radio_button[i].value;
                document.getElementById("buy_id").innerHTML = item;
            }
            if (radio_button[++i].checked) {
                item = radio_button[i].value;
                document.getElementById("buy_id").innerHTML = item;
            }
            if (radio_button[++i].checked) {
                item = radio_button[i].value;
                document.getElementById("buy_id").innerHTML = item;
            }
            if (radio_button[++i].checked) {
                item = radio_button[i].value;
                document.getElementById("buy_id").innerHTML = item;
            }
            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>

button

When designing this form, we know how many buttons there are and so we know that there are not too many if loops that we need to use to process all the buttons.

Note also how we use ++i to increment the radio_button array and access them one by one.  In ++i, the + is an operator and it means we pre-increment i before put it into the array radio_button.

 

Series Navigation<< Javascript: For loop
Javascript: Processing radio buttons using for loop >>