jQuery获取选中单选框的值

788

问题陈述很简单。我需要查看用户是否从一组单选按钮中选择了一个单选按钮。组中的每个单选按钮共享相同的id。

问题在于我无法控制表单生成的方式。以下是单选按钮控件代码的示例:

<input type="radio" name='s_2_1_6_0' value='Mail copy to my bill to address' id = "InvCopyRadio" onchange = 'SWESubmitForm(document.SWEForm2_0,s_4,"","1-DPWJJF")' style="height:20;width:25" tabindex=1997 >

另外,当选择一个单选按钮时,它不会向控件添加"checked"属性,只有文本已选中(我猜只是具有属性值为"checked"的属性)。以下是选定单选控件的外观:

<input type="radio" checked name='s_2_1_6_0' value='Mail copy to my bill to address' id = "InvCopyRadio" onchange = 'SWESubmitForm(document.SWEForm2_0,s_4,"","1-DPWJJF")' style="height:20;width:25" tabindex=1997 >

有谁能帮我编写jQuery代码,以获取选中单选按钮的值吗?


92
你有多个具有相同ID的元素?那真是太糟糕了。 - Matt Ball
2
可能是重复的问题:如何通过jQuery获取选中的单选框? - Alex Angas
它们都有相同的ID,这是如何工作的?通过ID进行评估时,评估不会在第一个匹配的元素处停止吗?这里的目的是什么,它们是在不同时间显示的动态元素吗? - Mark Carpenter Jr
3
ASP.NET MVC的@Html.RadioButtonFor辅助工具将生成所有单选按钮相同的id。糟糕。 - Triynko
尝试一下我的解决方案,它是所有解决方案中最好的。:: https://dev59.com/qWoy5IYBdhLWcg3wWcig#70798467 - pankaj
33个回答

阿里云服务器只需要99元/年,新老用户同享,点击查看详情
0
 <div class="col-md-12">
   <div class="form-radio">
       <input class="radio-outlined" id="accept_new_login1" type="radio" name="aNL" value="1">
       <label for="accept_new_login1" class="radio-teal">Yes</label>
        <input class="radio-outlined" id="accept_new_login2" type="radio" name="aNL" value="0">
        <label for="accept_new_login2" class="radio-teal">No</label>
   </div>
</div>

<script>
  $("input[name=aNL]").on("click" , function () {
    console.log("test" ,$("#accept_new_login").val() , this.value , this.id );
  })

 </script>

这个解决方案不仅简单,还能显示所选ID及其值。你可以查看我的输出。

enter image description here


0

如果您不知道特定名称或想要检查表单中的所有单选按钮,则可以使用全局变量仅检查每个单选按钮组的值一次:

        var radio_name = "";
        $("form).find(":radio").each(function(){
            if (!radio_name || radio_name != $(this).attr('name')) {
                radio_name = $(this).attr('name');
                var val = $('input[name="'+radio_name+'"]:checked').val();
                if (!val) alert($('input[name="'+radio_name+'"]:checked').val());
            }
        });`

0
    <input type="radio" name='s_2_1_6_0' value='Mail copy to my bill to address' id = "InvCopyRadio" onchange = 'SWESubmitForm(document.SWEForm2_0,s_4,"","1-DPWJJF")' style="height:20;width:25" tabindex=1997 >

$(function() {
      $("#submit").click(function() {
        alert($('input[name=s_2_1_6_0]:checked').val());
      });
    });`

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,