且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JS如何实现对name是数组的复选框的全选和反选以及取消选择

更新时间:2021-12-03 02:48:53

JS如何实现对name是数组的复选框的全选和反选以及取消选择? form内容如下:

因为PHP接收要用 数组形式的 复选框,正常情况下 JQ可如果是这种

直接使用 $("input[name=ptpt])即可。但是这种php接收的只是最后一个值,字符串。
<label><input type='checkbox' name='ptpt' value='a1' />a1</label>
<label><input type='checkbox' name='ptpt' value='a3' />a3</label>
<label><input type='checkbox' name='ptpt' value='a6' />a6</label>
<label><input type='checkbox' name='ptpt' value='a9' />a9</label>


这样PHP接收的是一个 ptpt的数组

<form method="post" id="form1" name="form1" action="" >
<label><input type='checkbox' name='ptpt[1]' value='a1' />a1</label>
<label><input type='checkbox' name='ptpt[3]' value='a3' />a3</label>
<label><input type='checkbox' name='ptpt[6]' value='a6' />a6</label>
<label><input type='checkbox' name='ptpt[9]' value='a9' />a9</label>
<input type="button" value="全选" onclick=""> 
<input type="button" value="反选" onclick=""> 
<input type="button" value="取消全选" onclick=""> 




<script src="jquery-1.7.2.min.js"></script>
<script>
$(function(){
var chks = $(':checkbox[name^="ptpt["]');  //匹配name开头为 ptpt[ 的部分
$(':button:eq(0)').click(function(){
chks.attr('checked','checked');
})
$(':button:eq(1)').click(function(){
chks.each(function(){
if($(this).attr('checked')=='checked')
$(this).removeAttr('checked');
else
$(this).attr('checked','checked');
});
})
$(':button:eq(2)').click(function(){
chks.removeAttr('checked');
})
})
</script>

本文转自  陈小龙哈   51CTO博客,原文链接:http://blog.51cto.com/chenxiaolong/1857132