如何使用 Javascript/Jquery 更改单选按钮的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10560402/
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
How to change the value of radio buttons using Javascript/Jquery
提问by Click Upvote
Say I have this radio:
假设我有这个收音机:
<form name="myForm">
<input type="radio" name="foo" value="1"> 1
<input type="radio" name="foo" value="2"> 2
</form>
I'm looking for a way to do something like this:
我正在寻找一种方法来做这样的事情:
document.myForm.foo.value = "2";
In order to dynamically select the 2nd radio button. Or a way to do the following using jquery.
为了动态选择第二个单选按钮。或者使用 jquery 执行以下操作的方法。
回答by Elliot Bonneville
jQuery selector:
jQuery 选择器:
$('input[value="2"][name="foo"]')
回答by Thulasiram
Use this:
用这个:
$('[name="foo"]').val(2);
回答by Chase
Since you requested this way, you could do:
既然你这样要求,你可以这样做:
document.myForm.foo[1].checked = true; //selects the 2nd radio button
document.myForm.foo[1].checked = true; //selects the 2nd radio button
Here's an example: http://jsfiddle.net/bTzqw/
这是一个例子:http: //jsfiddle.net/bTzqw/
回答by Selvakumar Arumugam
回答by elclanrs
If you grab all your radios by name in a jQuery collection, then you can select by index with eq()
.
如果您在 jQuery 集合中按名称获取所有收音机,那么您可以使用eq()
.
$('input[name="foo"]').eq(1) // 2nd input
回答by Danilo Valente
document.getElementsByName('foo')[1].check();//Or .checked = true