【问题标题】:How do I check/uncheck all checkboxes with a button using jQuery?如何使用 jQuery 使用按钮选中/取消选中所有复选框?
【发布时间】:2011-07-10 21:13:45
【问题描述】:

我正在尝试使用 jQuery 选中/取消选中所有复选框。现在通过选中/取消选中父复选框,所有子复选框都被选中/取消选中,父复选框的文本也被更改为选中/取消选中。

现在我想用输入按钮替换父复选框,并将按钮上的文本也更改为选中/取消选中。这是代码,有人可以调整代码吗?

    $( function() {
        $( '.checkAll' ).live( 'change', function() {
            $( '.cb-element' ).attr( 'checked', $( this ).is( ':checked' ) ? 'checked' : '' );
            $( this ).next().text( $( this ).is( ':checked' ) ? 'Uncheck All' : 'Check All' );
        });
        $( '.cb-element' ).live( 'change', function() {
            $( '.cb-element' ).length == $( '.cb-element:checked' ).length ? $( '.checkAll' ).attr( 'checked', 'checked' ).next().text( 'Uncheck All' ) : $( '.checkAll' ).attr( 'checked', '' ).next().text( 'Check All' );

        });
    });


   <input type="checkbox" class="checkAll" /> <b>Check All</b>

   <input type="checkbox" class="cb-element" /> Checkbox  1
   <input type="checkbox" class="cb-element" /> Checkbox  2
   <input type="checkbox" class="cb-element" /> Checkbox  3

【问题讨论】:

    标签: jquery checkbox


    【解决方案1】:

    试试这个:

    $(document).ready(function(){
        $('.check:button').toggle(function(){
            $('input:checkbox').attr('checked','checked');
            $(this).val('uncheck all');
        },function(){
            $('input:checkbox').removeAttr('checked');
            $(this).val('check all');        
        })
    })
    

    DEMO

    【讨论】:

    • -1 as toggle 不适合那样工作:api.jquery.com/toggle(至少是当前版本)
    • 只适用于一个按钮,如果你需要几个最好使用.click()
    • 注意:这个答案会检查表单中的每个复选框。 除非你愿意,否则请跳过。对于多个检查,这个答案帮助了我:stackoverflow.com/a/27148382/3448554
    • 这将不再起作用,.toggle(handler, handler) 在 jQuery 1.8 中被弃用并在 jQuery 1.9 中被删除。现在它所做的只是切换可见性。
    • 对于最新版本的 jQuery,.attr()removeAttr() 不应与“checked”属性一起使用。因为removeAttr() 将删除该属性而不是将其设置为false。如@richard-garside 回答中所述,应改用.prop('checked', true).prop('checked', false)
    【解决方案2】:

    这是我找到的最短的方法(需要 jQuery1.6+)

    HTML:

    <input type="checkbox" id="checkAll"/>
    

    JS:

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

    我正在使用 .prop,因为 .attr 不适用于 jQuery 1.6+ 中的复选框,除非您已将选中的属性明确添加到输入标签。

    例子-

    $("#checkAll").change(function () {
        $("input:checkbox").prop('checked', $(this).prop("checked"));
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <form action="#">
        <p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
        
        <fieldset>
            <legend>Loads of checkboxes</legend>
            <p><label><input type="checkbox" /> Option 1</label></p>
            <p><label><input type="checkbox" /> Option 2</label></p>
            <p><label><input type="checkbox" /> Option 3</label></p>
            <p><label><input type="checkbox" /> Option 4</label></p>
        </fieldset>
    </form>

    【讨论】:

    • 这个怎么用?有机会看到小提琴吗?
    • 简单的答案,但 OP 想要一个按钮
    • 这种方式如何“取消全选”?
    • @MichalSkop 此代码根据是否选中#checkAll 来选择或取消选择。如果要取消选中所有选项,则可以像这样使用 false 值 $("input:checkbox").prop('checked', false);
    • 谢谢,很简单!
    【解决方案3】:

    试试这个:

    HTML

    <input type="checkbox" name="all" id="checkall" />
    

    JavaScript

    $('#checkall:checkbox').change(function () {
       if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
       else $('input:checkbox').removeAttr('checked');
    });​
    

    DEMO

    【讨论】:

    • 是的,感谢这段代码完美,即使它从 DOM LEVEL 更改。我一直在努力编写代码,但即使我尝试了其他也无法正常工作的插件。这个是完美的。
    【解决方案4】:

    HTML

    <input type="checkbox" name="select_all" id="select_all" class="checkAll" />
    

    Javascript

        $('.checkAll').click(function(){
        if($(this).attr('checked')){
            $('input:checkbox').attr('checked',true);
        }
        else{
            $('input:checkbox').attr('checked',false);
        }
    });
    

    【讨论】:

    • 如果您使用的是 jQuery1.6+,请使用 .prop 而不是 .attr
    【解决方案5】:

    使用按钮切换复选框的解决方案,兼容 jQuery 1.9+ where toogle-event is no longer available:

    $('.check:button').click(function(){
          var checked = !$(this).data('checked');
          $('input:checkbox').prop('checked', checked);
          $(this).val(checked ? 'uncheck all' : 'check all' )
          $(this).data('checked', checked);
    });
    

    DEMO

    【讨论】:

    • 出于我的目的,将按钮替换为复选框,并将“input:checkbox”替换为类,效果很好!
    【解决方案6】:

    试试这个:

    $('.checkAll').on('click', function(e) {
         $('.cb-element').prop('checked', $(e.target).prop('checked'));
    });
    

    e是你做click时产生的事件,e.target是被点击的元素(.checkAll), 所以你只需要将元素的属性checked 与类.cb-element 一样放置元素 使用 .checkAll` 类。

    PS:请原谅我的英语不好!

    【讨论】:

    • 嘿鲁本,你应该在你的答案中添加评论,以便 OP 能够准确理解你是如何解决这个问题的
    • 感谢您的帮助@edi9999,我是初学者
    • IMO 这个答案更好,因为接受的答案将检查表单上的所有复选框,而您的模式让您可以轻松定位不同的 HTML 表单 $("#id ")$(".class") 元素通过 $('#all_news_items').on('click', function(e) { $('.news-item-option').prop('checked', $(e.target).prop('checked')); }); 之类的模式,而 checkall 函数不会干扰其他表单元素,因此您可以轻松添加新的 checkall:@987654329 @
    【解决方案7】:

    使用 jQuery 选中/取消选中所有带有中间属性的属性

    使用 getSelectedItems() 方法获取数组中的选中项

    来源Checkbox List Select / Unselect All with Indeterminate Master Check

    HTML

    <div class="container">
      <div class="card">
        <div class="card-header">
          <ul class="list-group list-group-flush">
            <li class="list-group-item">
              <input
                class="form-check-input"
                type="checkbox"
                value="selectAll"
                id="masterCheck"
              />
              <label class="form-check-label" for="masterCheck">
                Select / Unselect All
              </label>
            </li>
          </ul>
        </div>
        <div class="card-body">
          <ul class="list-group list-group-flush" id="list-wrapper">
            <li class="list-group-item">
              <input
                class="form-check-input"
                type="checkbox"
                value="item1"
                id="item1"
              />
              <label class="form-check-label" for="item1">
                Item 1
              </label>
            </li>
            <li class="list-group-item">
              <input
                class="form-check-input"
                type="checkbox"
                value="item2"
                id="item2"
              />
              <label class="form-check-label" for="item2">
                Item 2
              </label>
            </li>
            <li class="list-group-item">
              <input
                class="form-check-input"
                type="checkbox"
                value="item3"
                id="item3"
              />
              <label class="form-check-label" for="item3">
                Item 3
              </label>
            </li>
            <li class="list-group-item">
              <input
                class="form-check-input"
                type="checkbox"
                value="item4"
                id="item4"
              />
              <label class="form-check-label" for="item4">
                Item 4
              </label>
            </li>
            <li class="list-group-item">
              <input
                class="form-check-input"
                type="checkbox"
                value="item5"
                id="item5"
              />
              <label class="form-check-label" for="item5">
                Item 5
              </label>
            </li>
            <li class="list-group-item" id="selected-values"></li>
          </ul>
        </div>
      </div>
    </div>
    

    jQuery

      $(function() {
        // ID selector on Master Checkbox
        var masterCheck = $("#masterCheck");
        // ID selector on Items Container
        var listCheckItems = $("#list-wrapper :checkbox");
    
        // Click Event on Master Check
        masterCheck.on("click", function() {
          var isMasterChecked = $(this).is(":checked");
          listCheckItems.prop("checked", isMasterChecked);
          getSelectedItems();
        });
    
        // Change Event on each item checkbox
        listCheckItems.on("change", function() {
          // Total Checkboxes in list
          var totalItems = listCheckItems.length;
          // Total Checked Checkboxes in list
          var checkedItems = listCheckItems.filter(":checked").length;
    
          //If all are checked
          if (totalItems == checkedItems) {
            masterCheck.prop("indeterminate", false);
            masterCheck.prop("checked", true);
          }
          // Not all but only some are checked
          else if (checkedItems > 0 && checkedItems < totalItems) {
            masterCheck.prop("indeterminate", true);
          }
          //If none is checked
          else {
            masterCheck.prop("indeterminate", false);
            masterCheck.prop("checked", false);
          }
          getSelectedItems();
        });
    
        function getSelectedItems() {
          var getCheckedValues = [];
          getCheckedValues = [];
          listCheckItems.filter(":checked").each(function() {
            getCheckedValues.push($(this).val());
          });
          $("#selected-values").html(JSON.stringify(getCheckedValues));
        }
      });
    

    【讨论】:

      【解决方案8】:

      同意Richard Garside 的简短回答,但在$(this).prop("checked") 中不使用prop(),您可以使用checked 的原生JS 属性checkbox 之类的,

      $("#checkAll").change(function () {
          $("input:checkbox").prop('checked', this.checked);
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
      <form action="#">
          <p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
          
          <fieldset>
              <legend>Loads of checkboxes</legend>
              <p><label><input type="checkbox" /> Option 1</label></p>
              <p><label><input type="checkbox" /> Option 2</label></p>
              <p><label><input type="checkbox" /> Option 3</label></p>
              <p><label><input type="checkbox" /> Option 4</label></p>
          </fieldset>
      </form>

      【讨论】:

        【解决方案9】:

        你可以试试这个

            $('.checkAll').on('click',function(){
                $('.checkboxes').prop('checked',$(this).prop("checked"));
            });`
        

        .checkAll 类是控制批量操作的复选框

        【讨论】:

          【解决方案10】:

          如果用户选择所有复选框然后检查所有复选框将被选中,则以下代码将起作用,如果用户取消选择任何一个复选框,则将取消选中所有复选框。

          $("#checkall").change(function () {
              $("input:checkbox").prop('checked', $(this).prop("checked"));
          });
          
          $(".cb-element").change(function () {
            if($(".cb-element").length==$(".cb-element:checked").length)
              $("#checkall").prop('checked', true);
            else
              $("#checkall").prop('checked', false);
          });
          <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/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

          【讨论】:

            【解决方案11】:

            最佳解决方案 Check Fiddle

            $("#checkAll").change(function () {
                $("input:checkbox.cb-element").prop('checked', $(this).prop("checked"));
            });
            $(".cb-element").change(function () {
                    _tot = $(".cb-element").length                        
                    _tot_checked = $(".cb-element:checked").length;
            
                    if(_tot != _tot_checked){
                        $("#checkAll").prop('checked',false);
                    }
            });
            
            <input type="checkbox" id="checkAll"/> ALL
            
            <br />
            
            <input type="checkbox" class="cb-element" /> Checkbox  1
            <input type="checkbox" class="cb-element" /> Checkbox  2
            <input type="checkbox" class="cb-element" /> Checkbox  3
            

            【讨论】:

              【解决方案12】:

              试试这个

              $(".checkAll").click(function() {
                  if("checkall" === $(this).val()) {
                       $(".cb-element").attr('checked', true);
                       $(this).val("uncheckall"); //change button text
                  }
                  else if("uncheckall" === $(this).val()) {
                       $(".cb-element").attr('checked', false);
                       $(this).val("checkall"); //change button text
                  }
              });
              

              【讨论】:

              • 我试过你的脚本,但没有运气。如果我实施正确与否,你能看看这个吗..? Demo
              【解决方案13】:

              无耻的自我推销:there's a jQuery plugin for that.

              HTML:

              <form action="#" id="myform">
                  <div><input type="checkbox" id="checkall"> <label for="checkall"> Check all</label></div>
                  <fieldset id="slaves">
                      <div><label><input type="checkbox"> Checkbox</label></div>
                      <div><label><input type="checkbox"> Checkbox</label></div>
                      <div><label><input type="checkbox"> Checkbox</label></div>
                      <div><label><input type="checkbox"> Checkbox</label></div>
                      <div><label><input type="checkbox"> Checkbox</label></div>
                  </fieldset>
              </form>​
              

              JS:

              $('#checkall').checkAll('#slaves input:checkbox', {
                  reportTo: function () {
                      var prefix = this.prop('checked') ? 'un' : '';
                      this.next().text(prefix + 'check all');
                  }
              });​
              

              ...你就完成了。

              http://jsfiddle.net/mattball/NrM2P

              【讨论】:

                【解决方案14】:

                试试这个,

                <input type="checkbox" class="checkAll" onclick="$('input[type=checkbox][class=cb-element]').attr('checked',this.checked)">
                

                【讨论】:

                  【解决方案15】:

                  您可以使用this.checked来验证复选框的当前状态,

                  $('.checkAll').change(function(){
                      var state = this.checked; //checked ? - true else false
                  
                      state ? $(':checkbox').prop('checked',true) : $(':checkbox').prop('checked',false);
                  
                      //change text
                      state ? $(this).next('b').text('Uncheck All') : $(this).next('b').text('Check All')
                  });
                  

                  $('.checkAll').change(function(){
                      var state = this.checked;
                      state? $(':checkbox').prop('checked',true):$(':checkbox').prop('checked',false);
                      state? $(this).next('b').text('Uncheck All') :$(this).next('b').text('Check All')
                  });
                  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
                   <input type="checkbox" class="checkAll" /> <b>Check All</b>
                  
                     <input type="checkbox" class="cb-element" /> Checkbox  1
                     <input type="checkbox" class="cb-element" /> Checkbox  2
                     <input type="checkbox" class="cb-element" /> Checkbox  3

                  【讨论】:

                    【解决方案16】:

                    尝试下面的代码来选中/取消选中所有复选框

                    jQuery(document).ready(function() {
                        $("#check_uncheck").change(function() {
                            if ($("#check_uncheck:checked").length) {
                                $(".checkboxes input:checkbox").prop("checked", true);
                            } else {
                                $(".checkboxes input:checkbox").prop("checked", false);
                            }
                        })
                    });
                    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
                    <input type="checkbox" name="check_uncheck" id="check_uncheck" /> Check All/Uncheck All
                    <br/>
                    <br/>
                    <div class="checkboxes">
                        <input type="checkbox" name="check" id="check" /> Check Box 1
                        <br/>
                        <input type="checkbox" name="check" id="check" /> Check Box 2
                        <br/>
                        <input type="checkbox" name="check" id="check" /> Check Box 3
                        <br/>
                        <input type="checkbox" name="check" id="check" /> Check Box 4
                    </div>

                    试试这个Demo Link

                    还有另一种简短的方法可以做到这一点,请查看下面的示例。在此示例中,选中/取消选中所有复选框是否选中,如果选中则所有将被选中,如果不是全部将被取消选中

                    $("#check_uncheck").change(function() {
                        $(".checkboxes input:checkbox").prop("checked",$(this).is(':checked'));
                    })
                        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
                        <input type="checkbox" name="check_uncheck" id="check_uncheck" /> Check All/Uncheck All
                        <br/>
                        <br/>
                        <div class="checkboxes">
                            <input type="checkbox" name="check" id="check" /> Check Box 1
                            <br/>
                            <input type="checkbox" name="check" id="check" /> Check Box 2
                            <br/>
                            <input type="checkbox" name="check" id="check" /> Check Box 3
                            <br/>
                            <input type="checkbox" name="check" id="check" /> Check Box 4
                        </div>

                    【讨论】:

                      【解决方案17】:
                       $(document).on('change', '.check-all', function () {
                         if($(this).prop('checked')) {
                            $('.check-box').prop('checked', true)
                         }else {
                            $('.check-box').prop('checked', false);
                         }
                      

                      【讨论】:

                        【解决方案18】:

                        如果你想取消选中页面上的所有复选框,最简单的方法是这样的:

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

                        【讨论】:

                          【解决方案19】:

                          我知道这个问题很老,但我注意到大多数人都在使用复选框。接受的答案使用一个按钮,但不能与多个按钮一起使用(例如,一个在页面顶部的一个在底部)。所以这是一个兼具两者的修改。

                          HTML

                          <a href="#" class="check-box-machine my-button-style">Check All</a>
                          

                          jQuery

                          var ischecked = false;
                          $(".check-box-machine").click(function(e) {
                              e.preventDefault();
                              if (ischecked == false) {
                                  $("input:checkbox").attr("checked","checked");
                                  $(".check-box-machine").html("Uncheck All");
                                  ischecked = true;
                              } else {
                                  $("input:checkbox").removeAttr("checked");
                                  $(".check-box-machine").html("Check All");
                                  ischecked = false;
                              }
                          });
                          

                          这将允许您拥有任意数量的按钮来更改文本和复选框值。我包含了一个e.preventDefault() 调用,因为这将阻止页面由于href="#" 部分而跳到顶部。

                          【讨论】:

                            【解决方案20】:
                            $(function () {
                                $('input#check_all').change(function () {
                                    $("input[name='input_ids[]']").prop('checked', $(this).prop("checked"));
                                });
                            });
                            

                            【讨论】:

                            • 能否请您 edit 解释为什么这段代码回答了这个问题?不鼓励仅使用代码的答案,因为它们不教授解决方案。
                            【解决方案21】:

                            这是一个链接,用于选中和取消选中父复选框以及所有子复选框被选中和取消选中。

                            jquery check uncheck all checkboxes Using Jquery With Demo

                            $(function () {
                                    $("#select-all").on("click", function () {
                                        var all = $(this);
                                        $('input:checkbox').each(function () {
                                            $(this).prop("checked", all.prop("checked"));
                                        });
                                    });
                                });
                            

                            【讨论】:

                              【解决方案22】:
                              <script type="text/javascript">
                                  function myFunction(checked,total_boxes){ 
                                       for ( i=0 ; i < total_boxes ; i++ ){ 
                                         if (checked){   
                                           document.forms[0].checkBox[i].checked=true; 
                                          }else{  
                                           document.forms[0].checkBox[i].checked=false; 
                                          } 
                                      }   
                                  } 
                              </script>
                                  <body>
                                      <FORM> 
                                          <input type="checkbox" name="checkBox" >one<br> 
                                          <input type="checkbox" name="checkBox" >two<br> 
                                          <input type="checkbox" name="checkBox" >three<br> 
                                          <input type="checkbox" name="checkBox" >four<br> 
                                          <input type="checkbox" name="checkBox" >five<br> 
                                          <input type="checkbox" name="checkBox" >six<br> 
                                          <input type="checkbox" name="checkBox" >seven<br> 
                                          <input type="checkbox" name="checkBox" >eight<br> 
                                          <input type="checkbox" name="checkBox" >nine<br>
                                          <input type="checkbox" name="checkBox" >ten<br>  s
                                          <input type=button name="CheckAll" value="Select_All" onClick="myFunction(true,10)"> 
                                          <input type=button name="UnCheckAll" value="UnCheck All Boxes" onClick="myFunction(false,10)"> 
                                      </FORM> 
                                  </body>
                              

                              【讨论】:

                                【解决方案23】:

                                将此添加到您的代码块中,甚至单击您的按钮

                                $('input:checkbox').attr('checked',false);
                                

                                【讨论】:

                                  【解决方案24】:
                                  $(document).ready( function() {
                                          // Check All
                                          $('.checkall').click(function () {          
                                              $(":checkbox").attr("checked", true);
                                          });
                                          // Uncheck All
                                          $('.uncheckall').click(function () {            
                                              $(":checkbox").attr("checked", false);
                                          });
                                      });
                                  

                                  【讨论】:

                                    【解决方案25】:

                                    如果所有项目都已/未选中,则使用取消选中/选中控制器检查全部

                                    JS:

                                    e = checkbox id t= checkbox (item) class n= checkbox 检查所有类

                                    function checkAll(e,t,n){jQuery("#"+e).click(function(e){if(this.checked){jQuery("."+t).each(function(){this.checked=true;jQuery("."+n).each(function(){this.checked=true})})}else{jQuery("."+t).each(function(){this.checked=false;jQuery("."+n).each(function(){this.checked=false})})}});jQuery("."+t).click(function(e){var r=jQuery("."+t).length;var i=0;var s=0;jQuery("."+t).each(function(){if(this.checked==true){i++}if(this.checked==false){s++}});if(r==i){jQuery("."+n).each(function(){this.checked=true})}if(i<r){jQuery("."+n).each(function(){this.checked=false})}})}
                                    

                                    HTML:

                                    检查所有控制类:chkall_ctrl

                                    <input type="checkbox"name="chkall" id="chkall_up" class="chkall_ctrl"/>
                                    <br/>
                                    1.<input type="checkbox" value="1" class="chkall" name="chk[]" id="chk1"/><br/>
                                    2.<input type="checkbox" value="2" class="chkall" name="chk[]" id="chk2"/><br/>
                                    3.<input type="checkbox" value="3" class="chkall" name="chk[]" id="chk3"/><br/>
                                    <br/>
                                    <input type="checkbox"name="chkall" id="chkall_down" class="chkall_ctrl"/>
                                    
                                    <script>
                                    jQuery(document).ready(function($)
                                    {
                                      checkAll('chkall_up','chkall','chkall_ctrl');
                                      checkAll('chkall_down','chkall','chkall_ctrl');
                                    });
                                     </script>
                                    

                                    【讨论】:

                                      猜你喜欢
                                      • 2012-06-27
                                      • 2013-09-09
                                      • 2017-04-22
                                      • 1970-01-01
                                      • 2016-12-21
                                      • 2014-05-23
                                      • 2017-06-19
                                      • 2018-04-14
                                      • 1970-01-01
                                      相关资源
                                      最近更新 更多