Checking a radio button in JQuery
Asked Answered
C

6

7

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.

Crime answered 12/10, 2010 at 12:30 Comment(0)
L
14

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

$('input[name=my_name][value=123]').attr('checked', true); // or 'checked'
Lactoprotein answered 12/10, 2010 at 12:38 Comment(0)
B
8

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);
Backbone answered 18/11, 2018 at 7:27 Comment(0)
M
1

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

    $('input[name=my_name][value=123]').prop("checked",true)
Mcgowan answered 11/5, 2016 at 12:10 Comment(1)
Not if you're using a pre 1.6 versionMouthful
C
1

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

Cherin answered 26/12, 2017 at 17:34 Comment(1)
Careful with this solution. I was using this to match up two radio selections (one was for desktop and one was for mobile) that I already had a click handler on. Triggering a click caused an infinite loop on click events. Using .prop() fixed this for me. Otherwise, this is the easiest solution in my mind,Kinfolk
A
0
$('input[name=field]:eq(1)').click();

Note : field = radio button name property

Amyamyas answered 2/12, 2019 at 8:2 Comment(0)
R
0

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()
Rinaldo answered 7/11, 2020 at 16:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.