简体   繁体   English

如何以编程方式取消选中已选中的复选框?

[英]How can I uncheck a checked checkbox programmatically?

Say I have the following sample: 说我有以下样本:

<input name="Opt1" id="Opt1" type="checkbox" value="1" alt="1948" title="RQlevel1" src="2" checked="checked" onclick="levels();"/>  <label style="cursor:pointer" for="OptID12851948">PADI Advanced Open Water</label>

<input name="Opt2" id="Opt2" type="checkbox" value="2" alt="1953" title="RQlevel2" src=""  onclick="levels();"/>  <label style="cursor:pointer" for="OptID19521953">PADI Rescue</label>

<input name="Opt3" id="Opt3" type="checkbox" value="3" alt="1957" title="RQlevel2" src=""  onclick="levels();"/>  <label style="cursor:pointer" for="OptID19521953">PADI Rescue2</label>

If I click PADI Advanced Open Water checkbox, which will then call the levels() JavaScript function, how can I programmatically uncheck this checked checkbox using jQuery? 如果我单击PADI Advanced Open Water复选框,然后调用levels()JavaScript函数,如何使用jQuery以编程方式取消选中此复选框?

I have tried the following but doesn't work: 我尝试了以下但不起作用:

if ($("input[value='1']:checked").attr("checked")){
    $("input[value='1']:checked").attr(“checked”, false);
}   

Use removeAttr : 使用removeAttr

$("input[value='1']:checked").removeAttr('checked');

Or with recent versions of jQuery, you can use prop : 或者使用最新版本的jQuery,您可以使用prop

$("input[value='1']:checked").prop('checked', false);

If your using jQuery 1.6 and up you should really use .prop() for this 如果你使用jQuery 1.6及以上,你应该真的使用.prop()

In addition your selector already determines that the input is checked. 此外,您的选择器已确定已选中输入。 There is no need to duplicate that by checking the attribute or propery. 没有必要通过检查属性或属性来复制它。

if ($("input[value='1']:checked").length) { 
    $("input[value='1']:checked").prop("checked", false); 
}    

However if you are using a version of jQuery lower than 1.6 this will work by using removeAttr(). 但是,如果您使用的jQuery版本低于1.6,则可以使用removeAttr()。

if ($("input[value='1']:checked").length) { 
    $("input[value='1']:checked").removeAttr("checked"); 
}    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM