看到网上有些用jQuery实现checkBox 全选/全不选 的代码,有些很长,并且有的用了each方式去遍历来实现全选。其实并没有必要。
checkBox 全选/全不选 的要求:
1.点击全选,下面元素全部选中。再次点击全选,下面元素全部取消勾选。
2.下面元素勾选时,如果全部勾选,全选框要选中。不是全部勾选时,全选框要取消勾选。
Html代码
<input type="checkBox" name="allSelect1" id="allSelect1" /><label for="allSelect1">jQuery全选</label>
<input type="checkBox" name="select1[]" id="select1_1" /><label for="select1_1">选择1</label>
<input type="checkBox" name="select1[]" id="select1_2" /><label for="select1_2">选择2</label>
<input type="checkBox" name="select1[]" id="select1_3" /><label for="select1_3">选择3</label>
<input type="checkBox" name="select1[]" id="select1_4" /><label for="select1_4">选择4</label>
<input type="checkBox" name="select1[]" id="select1_5" /><label for="select1_5">选择5</label>
<br /> <br /> <br />
<input type="checkBox" name="allSelect2" id="allSelect2" /><label for="allSelect2">javascript全选</label>
<input type="checkBox" name="select2[]" id="select2_1" /><label for="select2_1">选择1</label>
<input type="checkBox" name="select2[]" id="select2_2" /><label for="select2_2">选择2</label>
<input type="checkBox" name="select2[]" id="select2_3" /><label for="select2_3">选择3</label>
<input type="checkBox" name="select2[]" id="select2_4" /><label for="select2_4">选择4</label>
<input type="checkBox" name="select2[]" id="select2_5" /><label for="select2_5">选择5</label>
jQuery实现方式,jQuery非常强大和方便,但是也要注意灵活运用。
逻辑:当其余元素触发点击事件时,获取未选中的checkBox的数量,如果为0,那么将全选框变为勾选。如果不为0,则不勾选。
$(document).ready(function(){
$('#allSelect1').click(function(){
$("input[name='select1[]']").attr('checked',$(this).attr('checked'));
});
$("input[name='select1[]']").click(function(){
$('#allSelect1').attr('checked',!$("input[name='select1[]']:not(:checked)").length);
});
});
javascript实现方式。全选框的判断类似上面。
window.onload = function() {
var allSelect2 = document.getElementById('allSelect2');
var list = document.getElementsByName('select2[]');
allSelect2.onclick = function() {
for(var i=0;i<list.length;i++) {
list[i].checked = this.checked;
}
};
for(var i=0;i<list.length;i++) {
var select = list[i];
select.onclick = function() {
var flag = false;
for(var j=0;j<list.length;j++) {
if(!list[j].checked) {
flag=true;
break;
}
}
allSelect2.checked = !flag;
};
}
}