Get Value of Selected Radio Button

On this page we describe and demonstrate how to use JavaScript to get the value of the selected radio button in a group. We have defined the following getRadioVal function which returns the value of the selected radio button, or undefined if no radio button is checked:

function getRadioVal(form, name) {
    var val;
    // get list of radio buttons with specified name
    var radios = form.elements[name];
    
    // loop through list of radio buttons
    for (var i=0, len=radios.length; i<len; i++) {
        if ( radios[i].checked ) { // radio checked?
            val = radios[i].value; // if so, hold its value in val
            break; // and break out of for loop
        }
    }
    return val; // return value of checked radio or undefined if none checked
}

The following form demonstrates use of the getRadioVal function:

Demo: Get Value of Selected

Select a shipping method:

To use the function, pass a reference to the form and the name of the radio button group:

// get value of selected 'ship' radio button in 'demoForm'
var val = getRadioVal( document.getElementById('demoForm'), 'ship' );
alert(val);

Inside the function we get references to the radio buttons whose name matches that passed to the function. The result is a node list which we iterate through using a for loop. As we iterate through the loop, if the current radio button's checked property evaluates to true, we hold its value in a variable and break out of the for loop. The function returns the variable (val), which contains either the value of the selected radio button or undefined if none are selected.

Example Form Markup

Markup for the example form is displayed here:

<form action="#" method="post" class="demoForm" id="demoForm">
    <fieldset>
        <legend>Demo: Get Value of Selected</legend>
    
    <p>Select a shipping method:</p>
    <p>
        <label><input type="radio" name="ship" value="std" checked /> Standard Ground</label>
        <label><input type="radio" name="ship" value="2day" /> Second Day</label>
        <label><input type="radio" name="ship" value="1day" /> Overnight</label>
        <label><input type="radio" name="ship" value="hold" /> Pick up</label>
    </p>
    
    <p><button type="button" name="getVal">Get Value of Selected</button></p>
    
    </fieldset>
</form>

Get Value of Selected Radio Button Onsubmit

The following demonstrates how to use the getRadioVal function to get the value of the selected radio button in a group onsubmit:

document.getElementById('demoForm').onsubmit = function() {
    // this (keyword) refers to form to which onsubmit attached
    // 'ship' is name of radio button group
    var val = getRadioVal(this, 'ship');
    // display value obtained
    alert(val);
    // more code here ...
}