简体   繁体   English

如何使用javascript获取单选按钮的值

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

I need to obtain the value of a radio button using javascript我需要使用 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我使用 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. document.getElementById('selection').value 需要获取该值,但即使选择了第二个单选按钮,它也会不断为我提供第一个单选按钮的值。 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/ 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.尽管 Matt 的解决方案工作得非常好并解决了您的直接问题,但如果您经常查询 DOM,我也建议您开始研究 JavaScript 库,例如 JQuery。

With JQuery, your solution is a one-liner:使用 JQuery,您的解决方案是单行的:

var selectedValue = $("input[name=selection]:checked").val();

普通的javasript:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM