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

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

or

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

这样的事情存在吗?


当前回答

对于jQuery 1.6+

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

对于jQuery 1.5.x及以下版本

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

为了检查,

$('.myCheckbox').removeAttr('checked');

其他回答

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

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

if($('jquery_selector').is(“:checked”)){//某些代码}<script src=“https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js“></script>

如果您使用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);
        });
    }

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

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

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

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