如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 10:15:40  来源:igfitidea点击:

How to change the value of radio buttons using Javascript/Jquery

javascriptjqueryradio-button

提问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

Are you looking for something like $(':radio[name=foo]:eq(1)')

你在寻找类似的东西吗 $(':radio[name=foo]:eq(1)')

DEMO

演示

回答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