我尝试用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);

不工作:

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

不工作:

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

不工作:

你还有别的主意吗?我错过了什么?


当前回答

Attr接受两个字符串。

正确的做法是:

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

其他回答

为了防止有人在使用jQuery UI时试图实现这一点,你还需要刷新UI复选框对象以反映更新后的值:

$("#option2").prop("checked", true); // Check id option2
$("input[name='radio_options']").button("refresh"); // Refresh button set
$("#radio_1").attr('checked', true);
//or
$("#radio_1").attr('checked', 'checked');

令人惊讶的是,尽管有评论,最受欢迎和接受的答案忽略了触发适当的事件。确保您调用了.change(),否则所有“on change”绑定将忽略此事件。

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

jQuery 1.6中添加了另一个函数prop(),用于相同的目的。

$("#radio_1").prop("checked", true); 
$("input[name=inputname]:radio").click(function() {
    if($(this).attr("value")=="yes") {
        $(".inputclassname").show();
    }
    if($(this).attr("value")=="no") {
        $(".inputclassname").hide();
    }
});