【问题标题】:Toggle Checkboxes on/off打开/关闭复选框
【发布时间】:2011-05-09 19:05:19
【问题描述】:

我有以下几点:

$(document).ready(function()
{
    $("#select-all-teammembers").click(function() {
        $("input[name=recipients\\[\\]]").attr('checked', true);
    });                 
});

我想要id="select-all-teammembers" 在单击时在选中和未选中之间切换。想法?那不是几十行代码吗?

【问题讨论】:

    标签: jquery checkbox jquery-selectors toggle


    【解决方案1】:

    你可以写:

    $(document).ready(function() {
        $("#select-all-teammembers").click(function() {
            var checkBoxes = $("input[name=recipients\\[\\]]");
            checkBoxes.prop("checked", !checkBoxes.prop("checked"));
        });                 
    });
    

    在 jQuery 1.6 之前,当我们只有 attr() 而没有 prop() 时,我们曾经这样写:

    checkBoxes.attr("checked", !checkBoxes.attr("checked"));
    

    prop() 在应用于“布尔”HTML 属性时比attr() 具有更好的语义,因此在这种情况下通常首选它。

    【讨论】:

    • 这可能会变得很复杂,因为它基于第一个状态的状态(所以如果用户检查第一个,然后使用切换,他们将不同步)。稍作调整,使其基于切换的状态,而不是列表中的第一个复选框: $("input[name=recipients\[\]]").prop("checked", $(this).prop("选中"));
    • 使用 'prop' 也可以让 Zepto 工作。否则它将选中该框,但不会取消选中它。
    • "prop" 而不是 "attr" 做到了这一点:使用 "attr" 它切换一段时间然后停止,使用 "prop" 代替它按预期切换。 +1 更新。
    • 下面@2astalavista提到的$('input[type=checkbox]').trigger('click');更简洁,也触发了“change”事件。
    • 您能否编辑您的答案以支持@CookiesForDevo 的答案
    【解决方案2】:
    //this toggles the checkbox, and fires its event if it has    
    
    $('input[type=checkbox]').trigger('click'); 
    //or
    $('input[type=checkbox]').click(); 
    

    【讨论】:

    • 适用于 chrome 29 但不适用于 FF 17.0.7,有人可以确认吗?
    • 我一直在走改变财产的路线。对我来说,这是一种用于选中和取消选中复选框元素的出色且更灵活的方法。
    • 触发了不需要的事件。
    • 对于复选框,通常更建议触发“更改”事件,因为它们可以通过单击标签来更改。
    【解决方案3】:

    我知道这是旧的,但问题有点模棱两可,因为 toggle 可能意味着每个复选框都应该切换其状态,无论是什么状态。如果您有 3 个选中而 2 个未选中,则切换将使前 3 个未选中,最后 2 个选中。

    为此,这里的解决方案都不起作用,因为它们使所有复选框具有相同的状态,而不是切换每个复选框的状态。在许多复选框上执行$(':checkbox').prop('checked') 会返回所有.checked 二进制属性之间的逻辑与,即如果其中一个未选中,则返回值为false

    如果您想实际切换每个复选框状态而不是使它们都相等,则需要使用.each(),例如

       $(':checkbox').each(function () { this.checked = !this.checked; });
    

    请注意,处理程序中不需要$(this),因为所有浏览器中都存在.checked 属性。

    【讨论】:

    • 是的,这是切换所有复选框状态的正确答案!
    • 当你有很多复选框时,比使用 jQuery 触发点击要快几个数量级。
    【解决方案4】:

    这是您想要的另一种方式。

    $(document).ready(function(){   
        $('#checkp').toggle(
            function () { 
                $('.check').attr('Checked','Checked'); 
            },
            function () { 
                $('.check').removeAttr('Checked'); 
            }
        );
    });
    

    【讨论】:

    • @kst - 这是一个更好的方法 $('input[name=recipients\[\]]').toggle(this.checked);忘记课程。
    【解决方案5】:

    我认为触发点击更简单:

    $("#select-all-teammembers").click(function() {
        $("input[name=recipients\\[\\]]").trigger('click');
    });                 
    

    【讨论】:

      【解决方案6】:

      我能想到的最好方法。

      $('#selectAll').change(function () {
          $('.reportCheckbox').prop('checked', this.checked);
      });
      

      $checkBoxes = $(".checkBoxes");
      $("#checkAll").change(function (e) {
          $checkBoxes.prop("checked", this.checked);
      });   
      

      <input onchange="toggleAll(this)">
      function toggleAll(sender) {
          $(".checkBoxes").prop("checked", sender.checked);
      }
      

      【讨论】:

        【解决方案7】:

        使用这个插件:

        $.fn.toggleCheck  =function() {
               if(this.tagName === 'INPUT') {
                   $(this).prop('checked', !($(this).is(':checked')));
               }
        
           }
        

        然后

        $('#myCheckBox').toggleCheck();
        

        【讨论】:

        • 对我来说,在我更改 if 语句之前,您的解决方案不起作用:if(this[0].tagName === 'INPUT')
        【解决方案8】:

        从 jQuery 1.6 开始,您可以使用 .prop(function) 来切换每个找到的元素的选中状态:

        $("input[name=recipients\\[\\]]").prop('checked', function(_, checked) {
            return !checked;
        });
        

        【讨论】:

        • 优秀的答案。您是否碰巧知道更多关于将下划线作为第一个参数传递的信息?我在哪里可以了解更多信息?
        • 编辑:显然,它本质上是一种传递 null stackoverflow.com/questions/11406823/… 的手段
        【解决方案9】:

        这是一种切换复选框的 jQuery 方法,无需选择带有 html5 和标签的复选框:

         <div class="checkbox-list margin-auto">
            <label class="">Compare to Last Year</label><br>
            <label class="normal" for="01">
               <input id="01" type="checkbox" name="VIEW" value="01"> Retail units
            </label>
            <label class="normal" for="02">
                  <input id="02" type="checkbox" name="VIEW" value="02">  Retail Dollars
            </label>
            <label class="normal" for="03">
                  <input id="03" type="checkbox" name="VIEW" value="03">  GP Dollars
            </label>
            <label class="normal" for="04">
                  <input id="04" type="checkbox" name="VIEW" value="04">  GP Percent
            </label>
        </div>
        
          $("input[name='VIEW']:checkbox").change(function() {
            if($(this).is(':checked')) {  
                 $("input[name='VIEW']:checkbox").prop("checked", false);
             $("input[name='VIEW']:checkbox").parent('.normal').removeClass("checked");
                 $(this).prop("checked", true);
                 $(this).parent('.normal').addClass('checked');
            }
            else{
                 $("input[name='VIEW']").prop("checked", false);
                 $("input[name='VIEW']").parent('.normal').removeClass('checked');
            }    
        });
        

        http://www.bootply.com/A4h6kAPshx

        【讨论】:

          【解决方案10】:

          假设它是一个必须切换复选框的图像,这对我有用

          <img src="something.gif" onclick="$('#checkboxid').prop('checked', !($('#checkboxid').is(':checked')));">
          <input type="checkbox" id="checkboxid">
          

          【讨论】:

          • 由于这是您的第一个答案,请意识到最好遵循海报在问题中使用的模式 - 例如将 jQuery 代码放在文档就绪处理程序中,而不是内联标记.如果您有理由不这样做,请说明原因。
          【解决方案11】:

          如果您想单独切换每个框(或者只有一个框也可以):

          我建议使用 .each() ,因为如果你想发生不同的事情,它很容易修改,而且相对较短且易于阅读。

          例如:

          // toggle all checkboxes, not all at once but toggle each one for its own checked state:
          $('input[type="checkbox"]').each(function(){ this.checked = ! this.checked });
          
          // check al even boxes, uncheck all odd boxes:
          $('input[type="checkbox"]').each(function(i,cb){ cb.checked = (i%2 == 0); });
          
          // set all to checked = x and only trigger change if it actually changed:
          x = true;
          $('input[type="checkbox"]').each(function(){
              if(this.checked != x){ this.checked = x; $(this).change();}  
          });
          

          在旁注... 不知道为什么每个人都使用 .attr() 或 .prop() 来(取消)检查。

          据我所知,element.checked 在所有浏览器中的工作方式始终相同?

          【讨论】:

            【解决方案12】:

            Check-all 复选框应在特定条件下更新本身。尝试单击'#select-all-teammembers',然后取消选中几个项目并再次单击全选。你可以看到不一致。为了防止它使用以下技巧:

              var checkBoxes = $('input[name=recipients\\[\\]]');
              $('#select-all-teammembers').click(function() {
                checkBoxes.prop("checked", !checkBoxes.prop("checked"));
                $(this).prop("checked", checkBoxes.is(':checked'));
              }); 
            

            顺便说一句,所有复选框 DOM 对象都应按上述方式缓存。

            【讨论】:

              【解决方案13】:

              你可以用这个

              $("#chkAll").on("click",function(){
                  $("input[name=checkBoxName]").prop("checked",$(this).prop("checked"));
              });
              

              【讨论】:

                【解决方案14】:
                jQuery("#checker").click(function(){
                    jQuery("#mydiv :checkbox").each(function(){
                        this.checked = true;
                    });
                });
                jQuery("#dechecker").click(function(){
                    jQuery("#mydiv :checkbox").each(function(){
                        this.checked = false;
                    });
                });
                jQuery("#checktoggler").click(function(){
                    jQuery("#mydiv :checkbox").each(function(){
                        this.checked = !this.checked;
                    });
                });
                

                ;)

                【讨论】:

                  【解决方案15】:

                  你也可以这样写

                  $(function() {
                      $("#checkbox-toggle").click(function() {
                          $('input[type=checkbox][name=checkbox_id\\[\\]]').click();
                      });
                  });
                  

                  当用户点击id为'#checkbox-toggle'的按钮时,只需要调用复选框的点击事件。

                  【讨论】:

                    【解决方案16】:

                    更好的方法和用户体验

                    $('.checkall').on('click', function() {
                       var $checks  = $('checks');
                       var $ckall = $(this);
                    
                        $.each($checks, function(){
                            $(this).prop("checked", $ckall.prop('checked'));
                        });
                    });
                    
                    $('checks').on('click', function(e){
                       $('.checkall').prop('checked', false);
                    });
                    

                    【讨论】:

                      【解决方案17】:
                      <table class="table table-datatable table-bordered table-condensed table-striped table-hover table-responsive">
                      <thead>
                          <tr>
                              <th class="col-xs-1"><a class="select_all btn btn-xs btn-info"> Select All </a></th>
                              <th class="col-xs-2">#ID</th>
                          </tr>
                      </thead>
                      <tbody>
                          <tr>
                              <td><input type="checkbox" name="order333"/></td>
                              <td>{{ order.id }}</td>
                          </tr>
                          <tr>
                              <td><input type="checkbox" name="order334"/></td>
                              <td>{{ order.id }}</td>
                          </tr>
                      </tbody>                  
                      </table>
                      

                      试试:

                      $(".table-datatable .select_all").on('click', function () {
                          $("input[name^='order']").prop('checked', function (i, val) {
                              return !val;
                          });
                      });
                      

                      【讨论】:

                        【解决方案18】:

                        这个很适合我。

                           $("#checkall").click(function() {
                               var fruits = $("input[name=fruits\\[\\]]");
                                fruits.prop("checked", $(this).prop("checked"));
                            });
                        

                        【讨论】:

                        • 你确实意识到你给“checked”属性赋予了它已经拥有的完全相同的值,对吧?是不是有点尴尬?你显然是想在它前面放一个! 标志..
                        【解决方案19】:

                        最基本的例子是:

                        // get DOM elements
                        var checkbox = document.querySelector('input'),
                            button = document.querySelector('button');
                        
                        // bind "cilck" event on the button
                        button.addEventListener('click', toggleCheckbox);
                        
                        // when clicking the button, toggle the checkbox
                        function toggleCheckbox(){
                          checkbox.checked = !checkbox.checked;
                        };
                        <input type="checkbox">
                        <button>Toggle checkbox</button>

                        【讨论】:

                          【解决方案20】:

                          在我的猜测中,建议正常变体的最正确的人是 GigolNet Gigolashvili,但我想建议更漂亮的变体。检查一下

                          $(document).on('click', '.fieldWrapper > label', function(event) {
                              event.preventDefault()
                              var n = $( event.target ).parent().find('input:checked').length
                              var m = $( event.target ).parent().find('input').length
                              x = n==m? false:true
                              $( event.target ).parent().find('input').each(function (ind, el) {
                                  // $(el).attr('checked', 'checked');
                                  this.checked = x
                              })
                          })
                          

                          【讨论】:

                            【解决方案21】:

                            分别设置 'checked' 或 null 而不是 true 或 false 即可。

                            // checkbox selection
                            var $chk=$(':checkbox');
                            $chk.prop('checked',$chk.is(':checked') ? null:'checked');
                            

                            【讨论】:

                              【解决方案22】:

                              此代码将在单击 Web 模板中使用的任何切换开关动画器时切换复选框。替换代码中可用的“.onoffswitch-label”。 “checkboxID”是此处切换的复选框。

                              $('.onoffswitch-label').click(function () {
                              if ($('#checkboxID').prop('checked')) 
                               {
                                 $('#checkboxID').prop('checked', false);
                               }
                              else 
                               {
                                 $('#checkboxID').prop('checked', true);
                               }
                              });
                              

                              【讨论】:

                                【解决方案23】:

                                还有一个更简单的方法

                                首先给你的复选框一个类示例 'id_chk'

                                然后在复选框内将控制“id_chk”复选框的状态:

                                &lt;input type='checkbox' onchange='js:jQuery(".id_chk").prop("checked", jQuery(this).prop("checked"))' /&gt;

                                就是这样,希望对你有帮助

                                【讨论】:

                                  猜你喜欢
                                  • 1970-01-01
                                  • 2018-06-27
                                  • 1970-01-01
                                  • 2018-06-11
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 1970-01-01
                                  • 2019-06-15
                                  • 1970-01-01
                                  相关资源
                                  最近更新 更多