简体   繁体   中英

How to disable all checkbox with use of foreach in jQuery

I want to disable all checkbox when click all 'select all'.

How is this possible using jQuery?

JavaScript:

Here categories[] is name of checkbox which is in foreach loop

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

Just use 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 

Give all your checkbox a class (ex: class='ck').

Then :

$('.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> 

This will work for you.

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

you can enable disable checkboxes with jquery like this.

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

Have a look at this demo .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM