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


当前回答

对于多个单选按钮,您必须在单选按钮标签上放置相同的name属性。 例如;

<input type="radio" name"gender" class="select_gender" value="male">
<input type="radio" name"gender" class="select_gender" value="female">

一旦你有了单选选项,现在你可以像下面这样使用jQuery代码来获得选中/选中的单选选项的值。

$(document).on("change", ".select_gender", function () {
   console.log($(this).val());    // Here you will get the current selected/checked radio option value
});

注意:使用$(document)是因为如果单选按钮是在DOM 100%加载后创建的,那么你需要它,因为如果你不使用$(document),那么jQuery将不知道新创建的单选按钮的范围。像这样调用jQuery事件是一个很好的实践。

其他回答

<div id="subscriptions">
 Company Suscription: <input type="radio" name="subsrad" value="1">
 Customer Subscription:<input type="radio" name="subsrad" value="2">
 Manully Set:<input type="radio" name="subsrad" value="MANUAL">
 NO Subscription:<input type="radio" name="subsrad" value="0">
 </div>

和处理jquery警报的值设置/通过div id更改:

$("#subscriptions input") // select the radio by its id
    .on('change', function(){ // bind a function to the change event
    alert($('input[name="subsrad"]:checked', '#subscriptions').val());
            });

这是如此简单....:-}

获取选中单选按钮值的最简单方法如下:

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

选择器之间不应使用空格。

我不是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示例。

下面是获取选定单选按钮值的简短版本

var value = $(":radio:checked").val()

你可以在javascript/jQuery中通过Id获取所选单选按钮的值。

$("#InvCopyRadio:checked").val();

我希望这能有所帮助。