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

不工作:

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


当前回答

我使用这个代码:

我为英语感到抱歉。

var $j = jQuery.noConflict(); $j(function() { // add handler $j('#radio-1, #radio-2').click(function(){ // find all checked and cancel checked $j('input:radio:checked').prop('checked', false); // this radio add cheked $j(this).prop('checked', true); }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <fieldset class="section"> <legend>Radio buttons</legend> <label> <input type="radio" id="radio-1" checked> Option one is this and that&mdash;be sure to include why it's great </label> <br> <label> <input type="radio" id="radio-2"> Option two can be something else </label> </fieldset>

其他回答

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

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

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

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

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

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

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

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

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

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

干杯!

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

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("#radio_1").attr('checked', 'checked');

这就是HTML属性