我有带有复选框“删除”数组和一个复选框“togglechbx”的 HTML 表单,用于切换所有复选框以选中/取消选中。因此,当没有选中任何 delete[] 时,必须禁用“delete-selected-btn”并且必须自动取消选中复选框“togglechbx”。
下面的 javascript 可以解决问题,但我将它与不同的 stackoverflow 示例结合在一起。这就是为什么它看起来如此丑陋和凌乱。你们能看看,如果有什么方法可以让它更短更干净吗?先感谢您。
<form id="show-images">
<input id="togglechbx" type="checkbox" onClick="toggle(this);" />
<input type="checkbox" class="delete-img" name="delete[]" value="1"/>
<input type="checkbox" class="delete-img" name="delete[]" value="2"/>
<input type="checkbox" class="delete-img" name="delete[]" value="3"/>
<button id="delete-selected-btn" type="submit" disabled="disabled">Delete selected</button></form>
<script>
$('.delete-img').change(function(){
var arrlenght = $("#show-images input:checkbox:checked").length;
if ( arrlenght > 0){
if ( arrlenght == 1 && document.getElementById("togglechbx").checked) {
$("#togglechbx").prop("checked", false);
$('#delete-selected-btn').attr("disabled", "disabled");
return false;
}
// any one from delete is checked
$('#delete-selected-btn').removeAttr("disabled");
}else{
// none is checked
$('#delete-selected-btn').attr("disabled", "disabled");
}});
function toggle(source) {
checkboxes = document.getElementsByName('delete[]');
for(var i=0, n=checkboxes.length; i<n; i++) {
checkboxes[i].checked = source.checked;
if ($("#show-images input:checkbox:checked").length > 0){
$('#delete-selected-btn').removeAttr("disabled");
}else{
// none is checked
$('#delete-selected-btn').attr("disabled", "disabled");
}
}
}
</script>