如何使用jQuery勾选所有复选框?

168

我不是jQuery专家,但我尝试为我的应用程序创建一个小脚本。我想检查所有复选框,但它没有正常工作。

首先我尝试使用 attr,然后我尝试了 prop,但我做错了什么。

我先尝试了这个:

$("#checkAll").change(function(){

  if (! $('input:checkbox').is('checked')) {
      $('input:checkbox').attr('checked','checked');
  } else {
      $('input:checkbox').removeAttr('checked');
  }       
});

但这并没有起作用。

下一步:这比上面的代码效果更好。

$("#checkAll").change(function(){

  if (! $('input:checkbox').is('checked')) {
      $('input:checkbox').prop('checked',true);
  } else {
      $('input:checkbox').prop('checked', false);
  }       
});

两个例子都无法工作。

JSFiddle: http://jsfiddle.net/hhZfu/4/


可能是重复的问题:.prop() vs .attr() - Liam
1
这是一个链接,指向我的 CodePen,它恰好实现了这个功能:https://codepen.io/nickhq/pen/pZJVEr - Nixon Kosgei
27个回答

389

你需要使用.prop()来设置checked属性。

$("#checkAll").click(function(){
    $('input:checkbox').not(this).prop('checked', this.checked);
});

演示:Fiddle


1
哇,谢谢你的快速回答。这个很好用,但是在我的应用程序中我有一个假的检查。当我刷新页面ctrl+r并点击复选框checkAll时,它不会全部选中。之后我必须再次检查才能成功。所以我需要2次单击checkAll,为什么不能一次单击就可以呢?我复制粘贴了那段代码,并创建了函数checkAll(),在复选框中设置了onclick="return checkAll()" - Ivan
3
如果你要使用jQuery,那就单独使用jQuery。不要把jQuery与内联JavaScript混在一起。例如,这种写法是不好的:<elementtag id="someID" onclick="javascript code here">。相反,可以用jQuery这样写:$('#someID').click(function() { checkAll() }); - cssyphus
5
你想知道这篇回答和这篇帖子之间的区别,为什么要使用 not(this).prop - Shaiju T
1
@ArunPJohny,在单个页面中,id应该是唯一的,我们如何使用相同的函数使用类示例https://jsfiddle.net/52uny55w/ - jvk
@ArunPJohny,感谢您的时间。我想向您学习关于jQuery的许多知识,您能给我一些建议吗? - jvk
显示剩余2条评论

69

只需使用 checkAllchecked 属性,并使用 prop() 而不是 attr 来设置 checked 属性。

演示页面

 $('#checkAll').click(function () {    
     $('input:checkbox').prop('checked', this.checked);    
 });

对于像checked这样的属性,请使用prop()方法而不是attr()方法。

自jQuery 1.6起,未设置的属性 .attr() 方法会返回undefined。要检索和更改表单元素的已选中、已选择或已禁用状态等DOM属性,请使用 .prop() 方法。

您为复选框设置了相同的id,应该使它们唯一。您最好使用一些类来管理有依赖关系的复选框,以便不包括您不想要的复选框。例如,$('input:checkbox')会选择页面上的所有复选框。如果页面上添加了新的复选框,则它们也将被选中/取消选中,这可能不是预期的行为。

实时演示

$('#checkAll').click(function () {    
    $(':checkbox.checkItem').prop('checked', this.checked);    
});

56

这里有完整的解决方案。

$(document).ready(function() {
    $("#checkedAll").change(function() {
        if (this.checked) {
            $(".checkSingle").each(function() {
                this.checked=true;
            });
        } else {
            $(".checkSingle").each(function() {
                this.checked=false;
            });
        }
    });

    $(".checkSingle").click(function () {
        if ($(this).is(":checked")) {
            var isAllChecked = 0;

            $(".checkSingle").each(function() {
                if (!this.checked)
                    isAllChecked = 1;
            });

            if (isAllChecked == 0) {
                $("#checkedAll").prop("checked", true);
            }     
        }
        else {
            $("#checkedAll").prop("checked", false);
        }
    });
});

Html应该是:

一个单选框,勾选三个复选框将会选择或取消选择它们。

<input type="checkbox" name="checkedAll" id="checkedAll" />

<input type="checkbox" name="checkAll" class="checkSingle" />
<input type="checkbox" name="checkAll" class="checkSingle" />
<input type="checkbox" name="checkAll" class="checkSingle" />

希望这对像我一样需要帮助的人有所帮助。

JS Fiddle https://jsfiddle.net/52uny55w/


3
我喜欢这个解决方案,因为如果您取消选中其中一个框,则“全选”框也会变为未选中状态。同样,如果您手动选中所有相应的框,则“全选”框也将被选中。这是很好的UI反馈! - HPWD
2
你可以通过将$("#checkedAll").change函数改为以下形式使其更简短:var val = this.checked; $(".checkSingle").each(function() { this.checked = val; }); - Gellie Ann
1
我认为最好将isAllChecked变量重命名为isThereUncheckedunChecked,这样可以更清楚地描述该变量的用途。 - Gellie Ann
1
我采用了这个解决方案,这正是我所寻找的,谢谢。 - Ajay Kumar
这正是我长期寻找的东西...谢谢! - Wilf

15

I think when user select all checkbox manually then checkall should be checked automatically or user unchecked one of them from all selected checkbox then checkall should be unchecked automically. here is my code..

$('#checkall').change(function () {
    $('.cb-element').prop('checked',this.checked);
});

$('.cb-element').change(function () {
 if ($('.cb-element:checked').length == $('.cb-element').length){
  $('#checkall').prop('checked',true);
 }
 else {
  $('#checkall').prop('checked',false);
 }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input type="checkbox" name="all" id="checkall" />Check All</br>
<input type="checkbox" class="cb-element" /> Checkbox  1</br>
<input type="checkbox" class="cb-element" /> Checkbox  2</br>
<input type="checkbox" class="cb-element" /> Checkbox  3


谢谢!我更喜欢这种方式,因为当所有复选框都被选中后,如果我们取消其中一个复选框,所有的复选框都会被取消选择。 - Rizqi N. Assyaufi

13

$(document).ready(function() {
  $("#parent").click(function() {
    $(".child").prop("checked", this.checked);
  });

  $('.child').click(function() {
    if ($('.child:checked').length == $('.child').length) {
      $('#parent').prop('checked', true);
    } else {
      $('#parent').prop('checked', false);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<p><input type="checkbox" id="parent" /> Check/Uncheck All</p>
<ul>
  <li>
    <input type="checkbox" class="child" /> Checkbox 1</li>
  <li>
    <input type="checkbox" class="child" /> Checkbox 2</li>
  <li>
    <input type="checkbox" class="child" /> Checkbox 3</li>
</ul>

HTML:

<p><input type="checkbox" id="parent" /> Check/Uncheck All</p>
<ul>
  <li>
    <input type="checkbox" class="child" /> Checkbox 1</li>
  <li>
    <input type="checkbox" class="child" /> Checkbox 2</li>
  <li>
    <input type="checkbox" class="child" /> Checkbox 3</li>
</ul>

jQuery:

$(document).ready(function() {
  $("#parent").click(function() {
    $(".child").prop("checked", this.checked);
  });

  $('.child').click(function() {
    if ($('.child:checked').length == $('.child').length) {
      $('#parent').prop('checked', true);
    } else {
      $('#parent').prop('checked', false);
    }
  });
});

8
为什么不试一下这个方法(在第二行的“form#”处,你需要放置你所用html表单的正确选择器):
$('.checkAll').click(function(){
    $('form#myForm input:checkbox').each(function(){
        $(this).prop('checked',true);
   })               
});

$('.uncheckAll').click(function(){
    $('form#myForm input:checkbox').each(function(){
        $(this).prop('checked',false);
   })               
});

你的HTML应该像这样:

你的HTML应该像这样:

<form id="myForm">
      <span class="checkAll">checkAll</span>
      <span class="uncheckAll">uncheckAll</span>
      <input type="checkbox" class="checkSingle"></input>
      ....
</form>

我希望你能够从这些信息中得到帮助。

5

我知道的最简单的方法:

$('input[type="checkbox"]').prop("checked", true);


2
$('#checkAll').on('change', function(){
    if($(this).attr('checked')){
        $('input[type=checkbox]').attr('checked',true);
    }
    else{
        $('input[type=checkbox]').removeAttr('checked');
    }
});

1
通常情况下,如果至少有一个从属复选框未被选中,则您还希望主复选框未被选中,并且如果所有从属复选框都被选中,则主复选框被选中:
/**
 * Checks and unchecks checkbox-group with a master checkbox and slave checkboxes
 * @param masterId is the id of master checkbox
 * @param slaveName is the name of slave checkboxes
 */
function checkAll(masterId, slaveName) {
    $master = $('#' + masterId);
    $slave = $('input:checkbox[name=' + slaveName + ']');

    $master.click(function(){
        $slave.prop('checked', $(this).prop('checked'));
        $slave.trigger('change');
    });

    $slave.change(function() {
        if ($master.is(':checked') && $slave.not(':checked').length > 0) {
            $master.prop('checked', false);
        } else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
        $master.prop('checked', 'checked');
    }
    });
}

如果您想启用任何控件(例如“全部删除”按钮或“添加某物”按钮),当至少选中一个复选框时启用,并在未选中复选框时禁用:

/**
 * Checks and unchecks checkbox-group with a master checkbox and slave checkboxes,
 * enables or disables a control when a checkbox is checked
 * @param masterId is the id of master checkbox
 * @param slaveName is the name of slave checkboxes
 */
function checkAllAndSwitchControl(masterId, slaveName, controlId) {
    $master = $('#' + masterId);
    $slave = $('input:checkbox[name=' + slaveName + ']');

    $master.click(function(){
        $slave.prop('checked', $(this).prop('checked'));
        $slave.trigger('change');
    });

    $slave.change(function() {
        switchControl(controlId, $slave.filter(':checked').length > 0);
        if ($master.is(':checked') && $slave.not(':checked').length > 0) {
            $master.prop('checked', false);
        } else if ($master.not(':checked') && $slave.not(':checked').length == 0) {
        $master.prop('checked', 'checked');
    }
    });
}

/**
 * Enables or disables a control
 * @param controlId is the control-id
 * @param enable is true, if control must be enabled, or false if not
 */
function switchControl(controlId, enable) {
    var $control = $('#' + controlId);
    if (enable) {
        $control.removeProp('disabled');
    } else {
        $control.prop('disabled', 'disabled');
    }
}

1
    <p id="checkAll">Check All</p>
<hr />
<input type="checkbox" class="checkItem">Item 1
<input type="checkbox" class="checkItem">Item 2
<input type="checkbox" class="checkItem">Item3

和jquery

$(document).on('click','#checkAll',function () {
     $('.checkItem').not(this).prop('checked', this.checked);
 });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接