<ul id="choose">
<li><label><input type="checkbox" value="1"> 吃饭</label></li>
<li><label><input type="checkbox" value="2"> 睡觉</label></li>
<li><label><input type="checkbox" value="3"> 打豆豆</label></li>
</ul>
<input type="checkbox" id="checkboxAll">
<input type="button" value="全选" class="btn" id="selectAll">
<input type="button" value="全不选" class="btn" id="unSelect">
<input type="button" value="反选" class="btn" id="reverse">
<input type="button" value="获得选中的所有值" class="btn" id="getValue">
因为是用jquery做的,所以必须先要导入jquery的js文件
<script src="${ctx!}/assets/js/jquery/jquery-2.0.3.min.js"></script>
1.点击全选,再点击全不选
$("#checkboxAll").click(function(){
if(this.checked){
$("#choose :checkbox").prop("checked", true);
}else{
$("#choose :checkbox").prop("checked", false);
}
});
2.点击全选
$("#selectAll").click(function () {
$("#choose:checkbox,#checkoxAll").prop("checked", true);
});
3.点击全不选
$("#unSelect").click(function () {
$("#choose:checkbox,#checkboxAll").prop("checked", false);
});
4.反选
$("#reverse").click(function () {
$("#choose:checkbox").each(function () {
$(this).prop("checked", !$(this).prop("checked"));
});
allchk();
});
函数allchk()就是用来检测全选框#checkAll应该是选中状态还是未选中状态的
function allchk(){
var chknum = $("#choose:checkbox").size();//选项总个数
var chk = 0;
$("#choose:checkbox").each(function () {
if($(this).prop("checked")==true){
chk++;
}
});
if(chknum==chk){//全选
$("#checkboxAll").prop("checked",true);
}else{//不全选
$("#checkboxAll").prop("checked",false);
}
}
5.获得所有选中值
$("#getValue").click(function(){
var valArr = "";
$("#choose :checkbox").each(function () {
if($(this).prop("checked")==true){
valArr+= $(this).val()+",";//转换为逗号隔开的字符串
}
});
alert(valArr);
});
6,赋值
for(var i=0;i<list.length;i++) {
$("input[name='checkbox']").each(function () { //根据name属性赋值
if ($(this).val() == list[i]) {
$(this).attr("checked", "checked");
}
});
7,获取被选中的值
var list=new Array();
$.each($('input:checkbox:checked'),function(){
list.push($(this).val());
});
<dd>
<label class="">
<input type="checkbox" value="1" name="checkbox" id="term_query_right">
查看</label>
<label class="">
<input type="checkbox" value="2" name="checkbox" id="term_add_right">
添加</label>
<label class="">
<input type="checkbox" value="3" name="checkbox" id="term_update_right">
修改</label>
<label class="">
<input type="checkbox" value="4" name="checkbox" id="term_delete_right">
删除</label>
</dd>