Javascript – How to get the value of a radio button with javascript

htmljavascript

I need to obtain the value of a radio button using javascript

I have a radio group called selection

<input type="radio" name="selection" id="selection" value="allClients" checked="checked" />All Clients<br />
          <input type="radio" name="selection" id="selection1" value="dateRange" />Date Range between 

I pass the value to another page using javascript

onclick="do_action1('liveClickCampaigns','contract_type='+document.getElementById('contract_type').value+'&beginDate='+document.getElementById('beginDate').value+'&endDate='+document.getElementById('endDate').value+'&selection1='+document.getElementById('selection1').value+'&selection='+document.getElementById('selection').value,'content');" type="button">

The document.getElementById('selection').value needs to get the value, but it keeps giving me the value of the first radio button even though the second is selected. The radio group is not within a form

Best Answer

Use:

function getRadioValue(name) {
    var group = document.getElementsByName(name);

    for (var i=0;i<group.length;i++) {
        if (group[i].checked) {
            return group[i].value;
        }
    }

    return '';
}

Application:

var selectedValue = getRadioValue('selection');

Demo:

http://www.jsfiddle.net/tqQWT/