2

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

Elitmiar
  • 35,072
  • 73
  • 180
  • 229

3 Answers3

7

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/

Matt
  • 74,352
  • 26
  • 153
  • 180
  • 2
    Change the string 'selection' with name variable so you can use it with all radiobuttons. Guess that was your intention ;) – Mark Baijens Sep 23 '10 at 12:25
3

Although Matt's solution works perfectly fine and solves your immediate problem, I would also recommend that you start looking into a JavaScript library, like JQuery, if you will be frequently querying the DOM.

With JQuery, your solution is a one-liner:

var selectedValue = $("input[name=selection]:checked").val();
Rokal
  • 485
  • 3
  • 7
  • 16
1

plain javasript:

var selectedValue = document.querySelector('input[name=selection]:checked').value;
Bernhard Wagner
  • 1,681
  • 12
  • 15