Using jquery, how do i check a radio button based

2020-07-04 07:03发布

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

标签: jquery
2条回答
等我变得足够好
2楼-- · 2020-07-04 07:55

Try this:

$('input[type=radio][value=' + preSelect + ']').attr('checked', true);
查看更多
smile是对你的礼貌
3楼-- · 2020-07-04 07:58

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

查看更多
登录 后发表回答