2013-07-15 49 views
9

Tôi có danh sách các nút radio. Tôi cần phải thực hiện một trong số họ kiểm tra dựa trên biến tôi có. Làm thế nào để tôi thực hiện điều này? Vấn đề là tôi không kiểm soát được danh sách nút radio sẽ trông như thế nào. Vì vậy, đây là mã của tôi:Sử dụng jquery, làm cách nào để tôi kiểm tra nút radio dựa trên giá trị biến?

<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 

Trả lời

14

bạn có thể sử dụng attribute equals selector để nhắm mục tiêu các đài phát thanh chính xác sau đó sử dụng .prop() để thiết lập thuộc tính kiểm tra

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

FIDDLE

+0

Tôi sẽ tham khảo danh sách radio cụ thể đó như thế nào? thông qua tên? Nếu vậy, làm thế nào? – Damien

+0

@Damien Tôi đã cập nhật câu trả lời của mình để cho bạn biết cách tham khảo danh sách cụ thể –

4

Hãy thử điều này:

$('input[type=radio][value=' + preSelect + ']').attr('checked', true); 
Các vấn đề liên quan