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

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

or

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

这样的事情存在吗?


当前回答

$("#mycheckbox")[0].checked = true;
$("#mycheckbox").attr('checked', true);
$("#mycheckbox").click();

最后一个将激发复选框的单击事件,其他的则不会。因此,如果您在onclick事件中为要激发的复选框设置了自定义代码,请使用最后一个。

其他回答

如果您使用ASP.NET MVC,生成许多复选框,然后必须使用JavaScript选择/取消选择所有选项,您可以执行以下操作。

HTML

@foreach (var item in Model)
{
    @Html.CheckBox(string.Format("ProductId_{0}", @item.Id), @item.IsSelected)
}

JavaScript

function SelectAll() {       
        $('input[id^="ProductId_"]').each(function () {          
            $(this).prop('checked', true);
        });
    }

    function UnselectAll() {
        $('input[id^="ProductId_"]').each(function () {
            $(this).prop('checked', false);
        });
    }

这将选择具有指定属性且值包含给定子字符串“ckbItem”的元素:

$('input[name *= ckbItem]').prop('checked', true);

它将选择名称属性中包含ckbItem的所有元素。

这可能会帮助某人。

HTML5

 <input id="check_box" type="checkbox" onclick="handleOnClick()">

JavaScript。

  function handleOnClick(){

      if($("#check_box").prop('checked'))
      {        
          console.log("current state: checked");
      }
      else
      {         
          console.log("current state: unchecked");
      }    
 }

我无法通过以下方式实现:

$("#cb").prop('checked', 'true');
$("#cb").prop('checked', 'false');

true和false都会选中该复选框。对我有用的是:

$("#cb").prop('checked', 'true'); // For checking
$("#cb").prop('checked', '');     // For unchecking

选中和取消选中

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