Javascript: Form with radio buttons

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

Now we look at how to pass values into a form with radio buttons.

<!DOCTYPE html>
    <title>Form Inputs</title>
        function submitForm(form) {
            var item;
            var rad_button = document.getElementsByName('radio_button');
            if (rad_button[0].checked) {
                item = rad_button[0].value;
            } else if (rad_button[1].checked) {
                item = rad_button[1].value;
            document.getElementById('buy_id').innerHTML = item;
<p>What would you like to buy this year?</p><br/>
    <input type='radio' name='radio_button' value='ipad' checked='checked'>iPad<br>
    <input type='radio' name='radio_button' value='camera'>Camera<br><br>
    <input type='button' value='Submit' onclick='submitForm(form)'>
<p>I bought a</p>
<h2 id='buy_id'></h2>

In order to access the value of radio buttons, we pass the name radio_button into a variable rad_button using getElementsByName.

You can also see how the value of the first button is accessed by rad_button[0] and the second value by rad_button[1].

A group of radio buttons is actually arranged in an Array datatype.  This is an important concept in HTML elements and we will get more into this in the later articles.

Series Navigation<< Javascript: A simple form
Javascript: For loop >>

Leave a comment

Leave a Reply