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

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

or

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

这样的事情存在吗?


当前回答

正如@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();

其他回答

如果您考虑使用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
}

纯JavaScript非常简单,开销也少得多:

var elements = document.getElementsByClassName('myCheckBox');
for(var i = 0; i < elements.length; i++)
{
    elements[i].checked = true;
}

此处的示例

你可以试试这个:

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

这可能是最短、最简单的解决方案:

$(".myCheckBox")[0].checked = true;

or

$(".myCheckBox")[0].checked = false;

更短的是:

$(".myCheckBox")[0].checked = !0;
$(".myCheckBox")[0].checked = !1;

这里还有一个jsFiddle。

2019年1月编辑

您可以使用:.prop(propertyName)-添加的版本:1.6

p{margin:20px 0 0;}b{颜色:红色;}标签{颜色:红色;}<!doctype html><html lang=“en”><head><meta charset=“utf-8”><script src=“https://code.jquery.com/jquery-1.10.2.js“></script></head><body><input id=“check1”type=“checkbox”checked=“checked”><label for=“check1”>检查此处</label><p></p><脚本>$(“input”).change(函数){var$input=$(this);$(“p”).html(“.attr(\”checked\“):<b>”+$input.attr“(”checked“)+”</b><br>“+“.prop(\”checked\“):<b>”+$input.prop(”checked“)+“</b><br>”+“.is(\”:checked \“):<b>”+$input.is(“:checked”)+“</b>”);}).change();</script></body></html>

论角度框架

示例1

在.html文件中

<input type="checkbox" (change)="toggleEditable($event)">

在.ts文件中

toggleEditable(event) {
     if ( event.target.checked ) {
         this.contentEditable = true;
    }
}

示例2

在.html文件中

<input type="checkbox" [(ngModel)]="isChecked" (change)="checkAction(isChecked ? 'Action1':'Action2')" />