根据 ID 在 jquery 中设置单选按钮“已选中”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3121785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set radio button 'checked' in jquery based on ID
提问by dzm
I have two radio buttons with the same name, one is checked by default. How can you check or uncheck a radio button in jQuery when selecting from id?
我有两个同名的单选按钮,默认情况下选中一个。从 id 中选择时,如何在 jQuery 中选中或取消选中单选按钮?
I've tried:
我试过了:
$('#radio1').attr('checked','checked');
$('#radio1').attr('checked', true);
Nothing seems to work.. any ideas?
似乎没有任何效果……有什么想法吗?
Thank you!
谢谢!
回答by Sarfraz
You can not have same id (#radio1
) more than once, use a class
instead.
您不能多次使用相同的 id ( #radio1
),请改用 a class
。
$('.radio1').attr('checked', true);
$('.radio2').attr('checked', true);
The id
should be used once per element per page.
本id
应每一次每页元素被使用。
If you want to check/uncheck on click
however, you may do like:
click
但是,如果您想选中/取消选中,您可能会喜欢:
$('#someid').click(function(){
$('#radio1').attr('checked', true);
});
Or
或者
$('#someid').click(function(){
$('#radio1').attr('checked', this.checked);
});
回答by Filippo Vitale
If you have the radios like:
如果你有这样的收音机:
<input type="radio" id="radio1" name="same-radio-name" />
<input type="radio" id="radio2" name="same-radio-name" />
So, to check the second and uncheck the first one:
因此,要检查第二个并取消选中第一个:
$('#radio2').attr('checked', true);
Viceversa:
反之亦然:
$('#radio1').attr('checked', true);
Just another thought, are you using the radio as a JQuery UIbutton? If so you may also need to refresh it like:
再想一想,您是否将收音机用作JQuery UI按钮?如果是这样,您可能还需要像这样刷新它:
$('#radio1').attr('checked', true).button("refresh");
回答by Josue Rodriguez
Well, if you wanna get a value from the input radio to upload this value from your database you can try with this simple code:
好吧,如果您想从输入无线电中获取一个值以从您的数据库上传该值,您可以尝试使用以下简单代码:
var selValue = $('input[name=rbnNumber]:checked').val();
Where you put the name of the variable "selValue" and inside of this you specific the name of the radio group "rbnNumber". All this inside the function that you work and done.
您将变量“selValue”的名称放在哪里,并在其中指定无线电组“rbnNumber”的名称。所有这些都在您工作和完成的功能中。