bba
bba

Reputation: 15231

Checking a radio button in JQuery

I need to programmatically check a radio button given its value. The form has an id and the input type obviously has a name (but no id). The only code I managed to get working so far is:

$('input[name=my_name]:eq(1)').attr('checked', 'checked');

But I'd like to be able to check it by explicitly providing the value.

Upvotes: 8

Views: 17322

Answers (6)

hoogw
hoogw

Reputation: 5535

Recommend use .click()

The other solution that only change radio option property or attribute

will NOT trigger radio event, you have to manually call radio event.

  $("#your_radio_option_ID_here").click()

Upvotes: 0

Moory Pc
Moory Pc

Reputation: 910

$('input[name=field]:eq(1)').click();

Note : field = radio button name property

Upvotes: 0

anand
anand

Reputation: 632

Below code worked with me, if I am assigning an ID to the radio button:

<input type="radio" id="rd_male" name="gender" value="Male" />
<input type="radio" id="rd_female" name="gender" value="Female" />
$('#rd_male').prop('checked', true);

Upvotes: 8

Poorna
Poorna

Reputation: 199

In order to select the radio button programmatically, you can call a jQuery trigger or $(".radioparentclass [value=radiovalue]")[0].click();

Upvotes: 1

Reza
Reza

Reputation: 3038

You should use prop instead of using attr . It's more recommended

    $('input[name=my_name][value=123]').prop("checked",true)

Upvotes: 1

nickf
nickf

Reputation: 546443

So you want to select the radio which has a particular value:

$('input[name=my_name][value=123]').attr('checked', true); // or 'checked'

Upvotes: 15

Related Questions