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

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

or

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

这样的事情存在吗?


当前回答

这是完整的答案使用jQuery

我测试了它,它100%工作:D

    // when the button (select_unit_button) is clicked it returns all the checed checkboxes values 
    $("#select_unit_button").on("click", function(e){

             var arr = [];

             $(':checkbox:checked').each(function(i){
                 arr[i] = $(this).val(); // u can get id or anything else
             });

              //console.log(arr); // u can test it using this in google chrome
    });

其他回答

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

如果您使用的是.prop('checked',true|false),并且没有更改复选框,则需要像这样添加触发器('click'):

// Check
$('#checkboxF1').prop( "checked", true).trigger('click');


// Uncheck
$('#checkboxF1').prop( "checked", false).trigger('click');

Use:

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

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

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

这可能会帮助某人。

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");
      }    
 }

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