簡體   English   中英

如何在jQuery中使用foreach禁用所有復選框

[英]How to disable all checkbox with use of foreach in jQuery

單擊全部“全選”時,我想禁用所有復選框。

使用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;
    }
}

只需使用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 

給您所有的復選框一個類(例如:class ='ck')。

然后 :

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

 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> 

這將為您工作。

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

您可以使用jquery啟用禁用復選框。

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

看看這個演示

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM