admin管理员组

文章数量:1295926

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.

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.

Share asked May 12, 2012 at 1:46 AliAli 267k268 gold badges591 silver badges785 bronze badges 2
  • Isn't the value of the 2nd radio button already 2?? – j08691 Commented May 12, 2012 at 1:50
  • So, do you want to cause a radio where the value is 2 to be selected, or do you want to change the value of the second radio button to 2? Your question is kind of unclear. – Daedalus Commented May 12, 2012 at 1:52
Add a ment  | 

6 Answers 6

Reset to default 3

jQuery selector:

$('input[value="2"][name="foo"]')

Use this:

$('[name="foo"]').val(2); 

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

DEMO

If you grab all your radios by name in a jQuery collection, then you can select by index with eq().

$('input[name="foo"]').eq(1) // 2nd input

Since you requested this way, you could do:

document.myForm.foo[1].checked = true; //selects the 2nd radio button

Here's an example: http://jsfiddle/bTzqw/

document.getElementsByName('foo')[1].check();//Or .checked = true

本文标签: How to change the value of radio buttons using JavascriptJqueryStack Overflow