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

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

or

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

这样的事情存在吗?


当前回答

另一种可能的解决方案:

    var c = $("#checkboxid");
    if (c.is(":checked")) {
         $('#checkboxid').prop('checked', false);
    } else {
         $('#checkboxid').prop('checked', true);
    }

其他回答

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

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

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

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

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

Use:

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

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

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

现代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的转换中对选中属性/属性的处理所做更改的不完整讨论。

你可以试试这个:

$('input[name="activity[task_state]"]').val("specify the value you want to check ")

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