Ali
Ali

Reputation: 267049

How to change the value of radio buttons using Javascript/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.

Upvotes: 2

Views: 16226

Answers (6)

Thulasiram
Thulasiram

Reputation: 8552

Use this:

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

Upvotes: 2

Chase
Chase

Reputation: 29549

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/

Upvotes: 0

elclanrs
elclanrs

Reputation: 94101

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

Upvotes: 0

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

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

DEMO

Upvotes: 0

Elliot Bonneville
Elliot Bonneville

Reputation: 53291

jQuery selector:

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

Upvotes: 3

Danilo Valente
Danilo Valente

Reputation: 11342

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

Upvotes: -1

Related Questions