【问题标题】:How to disable all checkbox with use of foreach in jQuery如何在 jQuery 中使用 foreach 禁用所有复选框
【发布时间】:2017-09-09 09:33:08
【问题描述】:

我想在单击全部“全选”时禁用所有复选框。

使用 jQuery 怎么可能?

JavaScript:

这里categories[]是foreach循环中复选框的名称

function checkAll(source) {
    checkboxes = document.getElementsByName('categories[]');

    for(var i=0, n=checkboxes.length;i<n;i++) {
        //checkboxes[i].checked = source.checked;
        checkboxes[i].disabled = source.disabled;
    }
}

【问题讨论】:

  • 不需要使用forech 来做到这一点。
  • 你遇到了什么问题?
  • 使用这个javascript ...所有复选框都没有禁用....你能解决这个javascript吗?如果解决了...那么我将实现 javascript。

标签: javascript jquery checkbox foreach


【解决方案1】:

您可以像这样使用 jquery 启用禁用复选框。

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

看看这个demo

【讨论】:

  • Thnx @Asim Shahzad
【解决方案2】:

这对你有用。

     <input type="checkbox" checked>A<br/>
     <input type="checkbox" checked>B<br/>
     <input type="checkbox">C<br/>
     <input type="checkbox" checked>D<br/>
     <input type="checkbox">E<br/>
     <button class="disableAll">Disable all</button>

     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <script>
      $(document).ready(function(){
      $(".disableAll").click(function(){
      $('input[type=checkbox]').each(function(){
      $(this).prop('disabled', true);
   })
    });
});

【讨论】:

  • 谢谢@Ajay Malhotra
【解决方案3】:

function uncheckAll() {
  $('input:checkbox').removeAttr('checked');
}

function disableAll() {
  $('input:checkbox').attr('disabled','true');
}
<input type="checkbox" checked>A<br/>
<input type="checkbox" checked>B<br/>
<input type="checkbox">C<br/>
<input type="checkbox" checked>D<br/>
<input type="checkbox">E<br/>
<button onclick="uncheckAll()">Uncheck all</button>
<button onclick="disableAll()">Disable all</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

    【解决方案4】:

    为所有复选框指定一个类(例如:class='ck')。

    然后:

    $('.ck').each(function(){
    $(this).prop('disabled', true);
    })
    

    【讨论】:

      【解决方案5】:

      只需使用prop('disabled', true)

      $('#mainChk').on('click', function(){
        var categories = $('.categories');
        categories.prop('disabled', !categories.prop('disabled'));
      });
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <input id="mainChk" type="checkbox" > Main
      <input type="checkbox" class="categories"> First
      <input type="checkbox" class="categories"> Second
      <input type="checkbox" class="categories"> Third

      【讨论】:

      • 感谢@Suren Srapyan
      • @RohanHapani 如果这有帮助,您可以接受它以帮助其他人轻松找到它
      猜你喜欢
      • 1970-01-01
      • 2019-03-05
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 2016-10-19
      • 2011-01-14
      • 2012-06-27
      • 1970-01-01
      相关资源
      最近更新 更多