Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jquery, how do i check a radio button based on a variable value?

Tags:

jquery

I have a list of radio buttons. I need to make one of them checked based on the variable i have. How do i accomplish this? The problem is i have no control of what the radio button list will look like. So here's my code:

<script>
var preSelect = 'Asian';
</script>

<input type="radio" name="CAT_Custom_378508" id="CAT_Custom_378508_0" value="Alaskan Native" />
Alaskan Native<br />
<input type="radio" name="CAT_Custom_378508" id="CAT_Custom_378508_1" value="Asian" />
Asian<br />
<input type="radio" name="CAT_Custom_378508" id="CAT_Custom_378508_2" value="African American" />
African American<br />
<input type="radio" name="CAT_Custom_378508" id="CAT_Custom_378508_3" value="Caucasian" />
Caucasian<br />
<input type="radio" name="CAT_Custom_378508" id="CAT_Custom_378508_4" value="Hispanic" />
Hispanic<br />
<input type="radio" name="CAT_Custom_378508" id="CAT_Custom_378508_5" value="Native American" />
Native American<br />
<input type="radio" name="CAT_Custom_378508" id="CAT_Custom_378508_6" value="Pacific Islander" />
Pacific Islander<br />
<input type="radio" name="CAT_Custom_378508" id="CAT_Custom_378508_7" value="Other" />
Other
like image 992
Damien Avatar asked Jul 15 '13 17:07

Damien


2 Answers

you can use the attribute equals selector to target the correct radio then use .prop() to set the checked property

$('input[name=CAT_Custom_378508][value=' + preSelect + ']').prop('checked',true)

FIDDLE

like image 98
wirey00 Avatar answered Sep 18 '22 02:09

wirey00


Try this:

$('input[type=radio][value=' + preSelect + ']').attr('checked', true);
like image 29
Danny Tremblay Avatar answered Sep 20 '22 02:09

Danny Tremblay