问题陈述很简单。我需要看看用户是否从无线电组中选择了一个单选按钮。组中的每个单选按钮共享相同的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”属性到控件中,只是文本检查(我猜只是没有值的属性检查)。下面是选定的无线电控件的外观

<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代码,可以帮助我得到选中单选按钮的值吗?


当前回答

我不是javascript的人,但我在这里找到了搜索这个问题。对于谁谷歌它和发现这里,我希望这有助于一些。所以,如果我们有一个单选按钮列表:

<div class="list">
    <input type="radio" name="b1" value="1">
    <input type="radio" name="b2" value="2" checked="checked">
    <input type="radio" name="b3" value="3">
</div>

我可以用这个选择器找到哪个选择了:

$('.list input[type="radio"]:checked:first').val();

即使没有选择任何元素,我仍然不会得到未定义的错误。因此,在获取元素的值之前,不需要编写额外的if语句。

下面是一个非常基本的jsfiddle示例。

其他回答

您可以使用父表单来查找无线电输入值。你不知道表单是如何生成的但你可以为表单提供类。

$('.form_class input[type=radio]:checked').val();

这里有两个单选按钮,分别是rd1和Radio1

<input type="radio" name="rd" id="rd1" />
<input type="radio" name="rd" id="Radio1" /> 

检查哪个单选按钮被选中的最简单方法是检查单个is(":checked")属性

if ($("#rd1").is(":checked")) {
      alert("rd1 checked");
   }
 else {
      alert("rd1 not checked");
   }

使用以下代码

$('input[name=your_radio_button_name]:checked').val();

请注意,值属性应该被定义,所以可以得到“男性”或“女性”在你的结果。

<div id='div_container'>
<input type="radio" name="Gender" value="Male" /> Male <br />
<input type="radio" name="Gender" value="Female" /> Female
</div>
$("#radioID") // select the radio by its id
    .change(function(){ // bind a function to the change event
        if( $(this).is(":checked") ){ // check if the radio is checked
            var val = $(this).val(); // retrieve the value
        }
    });

确保将其包装在DOM就绪函数中($(function(){…});美元(文档)时的功能 (){...});).

HTML Code
<input id="is_verified" class="check" name="is_verified" type="radio" value="1"/>
<input id="is_verified" class="check" name="is_verified" type="radio" checked="checked" value="0"/>
<input id="submit" name="submit" type="submit" value="Save" />

Javascript Code
$("input[type='radio'].check").click(function() {
    if($(this).is(':checked')) {
        if ($(this).val() == 1) {
            $("#submit").val("Verified & Save");
        }else{
            $("#submit").val("Save");
        }
    }
});