我尝试用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[type='radio'][name='userRadionButtonName']").prop('checked', true);

其他回答

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

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

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

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

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

你必须做

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

这就是HTML属性

得到的值:

$("[name='type'][checked]").attr("value");

设置的值:

$(this).attr({"checked":true}).prop({"checked":true});

单选按钮单击add attr checked:

$("[name='type']").click(function(){
  $("[name='type']").removeAttr("checked");
  $(this).attr({"checked":true}).prop({"checked":true});
});

最短的

radio_1.checked

checkBtn。Onclick = e=> { console.log (radio_1。检查); } 选择第一个单选并单击按钮 <!——问题html——> < >形式 < div id =“类型”> <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 > > < /形式 <!——测试html——> <按钮id = " checkBtn " >查看> < /按钮

这里是Jsfiddle代码片段

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