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

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

or

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

这样的事情存在吗?


当前回答

现代jQuery

使用.prop():

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

DOM API

如果您只使用一个元素,则始终可以访问基础HTMLInputElement并修改其.checked属性:

$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;

使用.prop()和.attr()方法代替此方法的好处是,它们将对所有匹配的元素进行操作。

jQuery 1.5.x及以下版本

.prop()方法不可用,因此需要使用.attr()。

$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);

注意,这是jQuery在1.6版之前的单元测试所使用的方法,比使用$('.myCheckbox').removeAttr('checked')更可取;因为如果最初选中了该框,则后者会改变对.reset()的调用在任何包含它的表单上的行为,这是一种微妙但可能不受欢迎的行为改变。

有关更多上下文,在1.6版发行说明和.prop()文档的Attributes vs.Properties(属性与财产)部分中,可以找到一些关于从1.5.x到1.6的转换中对选中属性/属性的处理所做更改的不完整讨论。

其他回答

Use:

$(".myCheckbox").attr('checked', true); // Deprecated
$(".myCheckbox").prop('checked', true);

如果要检查是否选中复选框:

$('.myCheckbox').is(':checked');

正如@livefree75所说:

jQuery 1.5.x及以下版本

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

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

但是在jQuery的新版本中,我们必须使用如下内容:

jQuery 1.6+

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

然后你可以这样做:

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

试试看:

$('#checkboxid').get(0).checked = true;  //For checking

$('#checkboxid').get(0).checked = false; //For unchecking

您还可以使用新方法扩展$.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()。

如果您碰巧在使用Bootstrap(可能是无意中)。。。

$('#myCheckbox').bootstrapToggle('on')
$('#myCheckbox').bootstrapToggle('off')

http://www.bootstraptoggle.com/