2

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.

2
  • Isn't the value of the 2nd radio button already 2?? 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. Commented May 12, 2012 at 1:52

6 Answers 6

3

jQuery selector:

$('input[value="2"][name="foo"]')
Sign up to request clarification or add additional context in comments.

3 Comments

what if I have more than 1 radios or inputs?
What if I have more than one sets of radios who both have values of 2? e.g <input name = foo value = 2 /> and <input name = bar value = 2 /> and I want to only select the foo one
@ClickUpvote: Answer updated to match two selectors as per request.
2

Use this:

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

Comments

0

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

DEMO

Comments

0

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

Comments

0

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.net/bTzqw/

Comments

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

3 Comments

Won't work because what if I want to move the radio options around?
If you want something that addresses that question it should be part of your original question.
it's just a fast example that shows you can select it by his name. So, the better solutiuon is to keep the same name but set different ids, like option1 and option2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.