【问题标题】:How to I get the value of a radio button with javascript如何使用 javascript 获取单选按钮的值
【发布时间】:2010-09-23 12:12:10
【问题描述】:

我需要使用 javascript 获取单选按钮的值

我有一个名为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 

我使用 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">

document.getElementById('selection').value 需要获取值,但即使选择了第二个单选按钮,它也会一直给我第一个单选按钮的值。单选组不在表单内

【问题讨论】:

    标签: javascript html


    【解决方案1】:

    用途:

    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 '';
    }
    

    应用:

    var selectedValue = getRadioValue('selection');
    

    演示:

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

    【讨论】:

    • 使用名称变量更改字符串“选择”,以便您可以将其与所有单选按钮一起使用。猜猜这是你的意图;)
    【解决方案2】:

    尽管 Matt 的解决方案工作得非常好并且解决了您的直接问题,但如果您将经常查询 DOM,我也建议您开始研究 JavaScript 库,例如 JQuery。

    使用 JQuery,您的解决方案是单行的:

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

    【讨论】:

      【解决方案3】:

      普通的javasript:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-01-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-06-02
        • 2013-06-29
        相关资源
        最近更新 更多