2017-04-13 66 views
-1

我想在全部“全选”时禁用所有复选框。如何使用jQuery中的foreach禁用所有复选框

这怎么可能使用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; 
    } 
} 
+1

不需要使用'forech'来做到这一点。 – vanloc

+0

你得到什么问题? –

+0

使用此javascript ...所有复选框不禁用....你能解决这个JavaScript?如果解决了......那么我会实现JavaScript。 –

回答

0

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

+0

谢谢@Suren Srapyan –

+0

@RohanHapani如果这有帮助,你可以接受这个帮助别人轻松找到它 –

0

给你所有的复选框一个类(例如:class ='ck')。

然后:

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

它不工作...只有第一个复选框被禁用... –

0

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>

+0

谢谢@Grandpa Guru .... –

0

这会为你工作。

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

+0

谢谢@Ajay Malhotra –

+0

如果这对你有用,你可以接受我的答案.. – Aaron

0

您可以启用像这样的jQuery禁用复选框。

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

看看这个demo

+0

Thnx @Asim Shahzad –

相关问题