我想这样做,使用jQuery勾选复选框:

$(".myCheckBox").checked(true);

or

$(".myCheckBox").selected(true);

这样的事情存在吗?


当前回答

要使用jQuery 1.6或更高版本选中复选框,只需执行以下操作:

checkbox.prop('checked', true);

要取消选中,请使用:

checkbox.prop('checked', false);

下面是我喜欢使用jQuery切换复选框的内容:

checkbox.prop('checked', !checkbox.prop('checked'));

如果使用jQuery 1.5或更低版本:

checkbox.attr('checked', true);

要取消选中,请使用:

checkbox.attr('checked', false);

其他回答

您还可以使用新方法扩展$.fn对象:

(function($)  {
   $.fn.extend({
      check : function()  {
         return this.filter(":radio, :checkbox").attr("checked", true);
      },
      uncheck : function()  {
         return this.filter(":radio, :checkbox").removeAttr("checked");
      }
   });
}(jQuery));

然后你可以这样做:

$(":checkbox").check();
$(":checkbox").uncheck();

或者,如果您使用其他使用这些名称的库,您可能希望为它们提供更多的唯一名称,如mycheck()和myuncheck()。

我们可以使用elementObject和jQuery来检查属性:

$(objectElement).attr('checked');

我们可以在所有jQuery版本中使用它,而不会出现任何错误。

更新:Jquery 1.6+具有替换attr的新prop方法,例如:

$(objectElement).prop('checked');

如果您考虑使用vanilla js而不是jquery,那么有一个解决方案:

//for one element: 
document.querySelector('.myCheckBox').checked = true /* or false */ //will select the first matched element
//for multiple elements:
for (const checkbox of document.querySelectorAll('.myCheckBox')) {
checkbox.checked = true //or false
}

你可以这样做,如果你有身份证来检查它

document.getElementById('ElementId').checked=false

这个要取消选中

document.getElementById('ElementId').checked=真

整体而言:

$("#checkAll").click(function(){
    $(".somecheckBoxes").prop('checked',$(this).prop('checked')?true:false);
});