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

不工作:

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


当前回答

试试这个

 $("input:checked", "#radioButton").val()

if选中返回True 如果未选中则返回False

jQuery v1.10.1

其他回答

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

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

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

干杯!

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

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

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

此外,你可以检查元素是否被选中:

if ($('.myCheckbox').attr('checked'))
{
   //do others stuff
}
else
{
   //do others stuff
}

你可以检查未检查的元素:

$('.myCheckbox').attr('checked',true) //Standards way

你也可以这样取消勾选:

$('.myCheckbox').removeAttr('checked')

您可以检查单选按钮:

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

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

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

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

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

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