开发者

How to I get the value of a radio button with javascript

开发者 https://www.devze.com 2023-01-17 02:33 出处:网络
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=\"check

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开发者_JS百科="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


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/


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();


plain javasript:

var selectedValue = document.querySelector('input[name=selection]:checked').value;
0

精彩评论

暂无评论...
验证码 换一张
取 消