如何用jQuery检查单选按钮? [英] How to check a radio button with jQuery?

查看:138
本文介绍了如何用jQuery检查单选按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试用jQuery检查单选按钮。这是我的代码:

 < 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>

和JavaScript:

  jQuery(#radio_1)。attr('checked',true); 

无效:

<$ p $ jQuery(input [value ='1'])。attr('checked',true);

无效:

<$ p $ jQuery('input:radio [name =type]')。filter('[value =1]')。attr('checked',true);

无效:

你有另一个想法?我错过了什么?

解决方案

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

  $(#radio_1)。prop(checked,true); 

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

  $(#radio_1)。attr('checked','checked'); 

提示:您可能还想调用然后在单选按钮上单击() change()请参阅评论以获取更多信息。


I try to check a radio button with 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:

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?

解决方案

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

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

For versions prior to (<) 1.6, use:

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

Tip: You may also want to call click() or change() on the radio button afterwards. See comments for more info.

这篇关于如何用jQuery检查单选按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆