[英]How to check and uncheck all checkboxes inside a div
我想取消選中'test'div中的所有checkboxex,而不選擇那些屬性被禁用的復選框。
<div id="test">
<input type="checkbox" id="check1" name="check1">
<input type="checkbox" id="check01" name="check01" disabled="disabled">
<input type="checkbox" id="check2" name="check2" disabled="disabled">
<input type="checkbox" id="check3" name="check3">
<input type="checkbox" id="check4" name="check4">
<input type="checkbox" id="check50" name="check50">
<input type="checkbox" id="check6" name="check6">
</div>
<input type="button" id="uncheckAll" onclick="uncheckAll('test')">
<script language="javascript">
function uncheckAll() {
$('#' + divid + ' :checkbox').attr('checked', false);
/*
This function uncheck all of the checkboxes, which i don't want, i want to
uncheck only checkboxes whose attributes are not disabled.
/*
}*/
</script>
您需要接受名為divId的參數,然后使用:enabled filter來過濾掉禁用的復選框
function uncheckAll(divid) {
$('#' + divid + ' :checkbox:enabled').prop('checked', false);
}
演示: 小提琴
如果沒有jQuery
function uncheckAll(divid) {
var checks = document.querySelectorAll('#' + divid + ' input[type="checkbox"]');
for(var i =0; i< checks.length;i++){
var check = checks[i];
if(!check.disabled){
check.checked = false;
}
}
}
演示: 小提琴
您可以為每個輸入采用公共類。 嘗試這個
<div id="test">
<input type="checkbox" id="check1" class="check" name="check1">
<input type="checkbox" id="check01" class="check" name="check01" disabled="disabled">
<input type="checkbox" id="check2" class="check" name="check2" disabled="disabled">
<input type="checkbox" id="check3" class="check" name="check3">
<input type="checkbox" id="check4" class="check" name="check4">
<input type="checkbox" id="check50" class="check" name="check50">
<input type="checkbox" id="check6" class="check" name="check6">
</div>
<input type="button" id="uncheckAll" onclick="uncheckAll()">
<script language="javascript">
function uncheckAll()
{
$("input.check").each(function(){
if($(this).prop('disabled')!=true)
{
$(this).attr('checked',false);
}
});
}
</script>
以下單行jQuery代碼將完成您的工作。
function uncheckAll(divid) {
$('#' + divid + ' :checkbox:not([disabled])').attr('checked', false);
}
最簡單的解決方案:
// index.html在<body>
創建:
<button type="button" id="desativar-tudo">Uncheck All</button>
<button type="button" id="ativar-tudo">Check All</button>
//之后創建:
<script type="text/javascript" src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function uncheckAll() {$('input').prop('checked', false);}
function CheckAll(){$('input').prop('checked', true);}
$('#desativar-tudo').click(uncheckAll);
$('#ativar-tudo').click(CheckAll);
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.