实现复选框全选/全不选切换
程序员文章站
2023-10-29 13:35:28
<input type=checkbox name=mm value=a onclick="checkitem(this, 'mmall')"><br>
<input type=checkbox name=mm value=b onclick="checkitem(this, 'mmall')"><br>
<input type=checkbox name=mm value=c onclick="checkitem(this, 'mmall')"><br>
<input type=checkbox name=mm value=d onclick="checkitem(this, 'mmall')"><br>
<input type=checkbox name=mm value=e onclick="checkitem(this, 'mmall')"><br><br>
<input type=checkbox name=mmall onclick="checkall(this, 'mm')">全选与不全选的切换
<script language=javascript>
function checkall(e, itemname)
{
var aa = document.getelementsbyname(itemname);
for (var i=0; i<aa.length; i++)
aa[i].checked = e.checked;
}
function checkitem(e, allname)
{
var all = document.getelementsbyname(allname)[0];
if(!e.checked) all.checked = false;
else
{
var aa = document.getelementsbyname(e.name);
for (var i=0; i<aa.length; i++)
if(!aa[i].checked) return;
all.checked = true;
}
}
</script>
ps:(当然若那个全选框是其它的控件比如是一个按钮,或者一个链接什么的话,那复选框里的 checkitem 点击事件可以去掉,以免出错)
<input type=checkbox name=mm value=b onclick="checkitem(this, 'mmall')"><br>
<input type=checkbox name=mm value=c onclick="checkitem(this, 'mmall')"><br>
<input type=checkbox name=mm value=d onclick="checkitem(this, 'mmall')"><br>
<input type=checkbox name=mm value=e onclick="checkitem(this, 'mmall')"><br><br>
<input type=checkbox name=mmall onclick="checkall(this, 'mm')">全选与不全选的切换
<script language=javascript>
function checkall(e, itemname)
{
var aa = document.getelementsbyname(itemname);
for (var i=0; i<aa.length; i++)
aa[i].checked = e.checked;
}
function checkitem(e, allname)
{
var all = document.getelementsbyname(allname)[0];
if(!e.checked) all.checked = false;
else
{
var aa = document.getelementsbyname(e.name);
for (var i=0; i<aa.length; i++)
if(!aa[i].checked) return;
all.checked = true;
}
}
</script>
ps:(当然若那个全选框是其它的控件比如是一个按钮,或者一个链接什么的话,那复选框里的 checkitem 点击事件可以去掉,以免出错)