简体   繁体   English

jQuery获取选定的单选按钮值

[英]Jquery to get the selected radio button value

i have 3 set of radio buttons while selecting any one of them i have to get the value of that radio. 我有3组单选按钮,同时选择其中任何一个,我必须获取该单选按钮的值。

iam using following code IAM使用以下代码

Daily<input type="radio" id="rad" value="daily" />
Weekly<input type="radio" id="rad" name="case" value="weekly"/>
None<input type="radio" id="rad" name="case" value="none"/>
alert("rad------"+$('#rad').val());

it alerts the radio button value first time only and multiple radio button seems to be as selected. 它仅第一次警告单选按钮值,并且似乎已选中多个单选按钮。

id of an element must be unique, so in this case you need to find the checked radio button with name case 元素的ID必须是唯一的,因此在这种情况下,您需要查找带有名称case的选中单选按钮

For that you can use the attribute equals selector along with :checked selector 为此,您可以将属性equals选择器:checked选择 一起使用

Daily <input type="radio" id="rad" name="case" value="daily" />
Weekly <input type="radio" id="rad" name="case" value="weekly" />
None <input type="radio" id="rad" name="case" value="none" />

alert("rad------"+$('input[type="radio"][name="case"]:checked').val());

Your problem may be in how you are detecting the change in event, you can do something like this: 您的问题可能在于如何检测事件的变化,您可以执行以下操作:

$('container input:radio').click(function(){
    alert("rad------"+$(this).val());
});

notes 笔记

:radio is short for [type=radio] :radio是[type = radio]的缩写

substitute container for the container, or use input#radio in the case of your example. 用容器代替容器,或者在您的示例中使用input#radio。 Generally it isn't a good idea to assign the same id to a bunch of inputs 通常,将相同的id分配给一堆输入不是一个好主意

Just to be a pedant - as Arun P Johny wrote IDs must be unique, but in his example he left the duplicate IDs in. 只是为了成为一个书呆子-正如Arun P Johny所写,ID必须是唯一的,但在他的示例中,他保留了重复的ID。

It should be: 它应该是:

Daily <input type="radio" name="case" value="daily" />
Weekly <input type="radio" name="case" value="weekly" />
None <input type="radio" name="case" value="none" />
alert("rad------"+$('input[type="radio"][name="case"]:checked').val());

See Two radio buttons share one "id"? 看到两个单选按钮共享一个“ id”吗? for more details. 更多细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM