问题陈述很简单。我需要看看用户是否从无线电组中选择了一个单选按钮。组中的每个单选按钮共享相同的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代码,可以帮助我得到选中单选按钮的值吗?


当前回答

如果你不知道具体的名称,或者想要检查表单中的所有无线电输入,你可以使用一个全局变量来检查每个无线电组的值,只检查一次: `

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

其他回答

在代码中,jQuery只查找输入的第一个实例 名称为q12_3,在本例中为1。你想要一个 输入名称为q12_3,即:已检查。

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

注意,上面的代码与使用的不一样 .(":检查")。 jQuery的是() 函数返回一个布尔值(true或false),而不是 元素。

只看名字

$(function () {
    $('input[name="EventType"]:radio').change(function () {
        alert($("input[name='EventType']:checked").val());
    });
});
$("#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(){…});美元(文档)时的功能 (){...});).

只使用。

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

就是这么简单。

另一种理解…工作:

HTML代码:

 <input type="radio" name="active_status" class="active_status" value="Hold">Hold 
 <input type="radio" name="active_status" class="active_status" value="Cancel">Cancel 
 <input type="radio" name="active_status" class="active_status" value="Suspend">Suspend

Jquery代码:

$(document).on("click", ".active_status", function () {
 var a = $('input[name=active_status]:checked').val();  
 (OR)   
 var a = $('.active_status:checked').val();
 alert(a);
});