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

不工作:

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


当前回答

有时以上的解决方案并不奏效,那么你可以试试下面的方法:

jQuery.uniform.update(jQuery("#yourElementID").attr('checked',true));
jQuery.uniform.update(jQuery("#yourElementID").attr('checked',false));

另一种方法是:

jQuery("input:radio[name=yourElementName]:nth(0)").attr('checked',true);

其他回答

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

如果属性名称不起作用,不要忘记id仍然存在。这个答案是给那些想知道你怎么做的人的。

$('input[id=element_id][value=element_value]').prop("checked",true);

因为属性名对我没用。请确保id和名字周围没有双引号或单引号。

干杯!

是的,这对我来说很管用:

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

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

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

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

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

提示:您可能还想随后在单选按钮上调用click()或change()。查看评论了解更多信息。

Attr接受两个字符串。

正确的做法是:

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