Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
325 views
in Technique[技术] by (71.8m points)

javascript - 如何使用jQuery检查单选按钮?(How to check a radio button with jQuery?)

I try to check a radio button with jQuery.

(我尝试用jQuery检查一个单选按钮。)

Here's my code:

(这是我的代码:)

<form>
    <div id='type'>
        <input type='radio' id='radio_1' name='type' value='1' />
        <input type='radio' id='radio_2' name='type' value='2' />
        <input type='radio' id='radio_3' name='type' value='3' /> 
    </div>
</form>

And the JavaScript:

(和JavaScript:)

jQuery("#radio_1").attr('checked', true);

Doesn't work:

(不起作用:)

jQuery("input[value='1']").attr('checked', true);

Doesn't work:

(不起作用:)

jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);

Doesn't work:

(不起作用:)

Do you have another idea?

(你有其他想法吗?)

What am I missing?

(我错过了什么?)

  ask by Alexis translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

For versions of jQuery equal or above (>=) 1.6, use:

(对于jQuery等于或大于(> =)1.6的版本,请使用:)

$("#radio_1").prop("checked", true);

For versions prior to (<) 1.6, use:

(对于(<)1.6之前的版本,请使用:)

$("#radio_1").attr('checked', 'checked');

Tip: You may also want to call click() or change() on the radio button afterwards.

(提示:您可能还想在之后调用单选按钮上的click()change() 。)

See comments for more info.

(有关详细信息,请参阅注释)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...