實現checkboxlist的全選

螢火蟲小Q發表於2012-07-29

第一種:利用客戶端控制元件實現
JS:

<script type="text/javascript">
function checkAll()
{
var checklist=document.getElementsByTagName("input");
for(var i=0;i<checklist.length;i++)
{
if(checklist[i].type=="checkbox")
{
checklist[i].checked=document.form1.ck.checked;
}
}
}
</script>

GridView控制元件:

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" >
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="產品編號" />
<asp:TemplateField>
<HeaderTemplate>
<input id="ck" type="checkbox" onclick="checkAll();" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="checkbox1" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

第二種:利用伺服器端控制元件實現
複製程式碼 程式碼如下:
protected void 全選_CheckedChanged(object sender, EventArgs e)
{
if (全選.Checked == true)
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox ck = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("checkbox1") as CheckBox;
if (ck!=null)
{
ck.Checked = true;
}
}
}
else
{
for (int i = 0; i < GridView1.Rows.Count; i++)
{
CheckBox ck = (CheckBox)GridView1.Rows[i].Cells[0].FindControl("checkbox1") as CheckBox;
if (ck != null)
{
ck.Checked = false;
}
}
}
}

或者,你可以像這樣來做:

<html>
<head><title></title></head>
<body>
<input type="checkbox" id="chkAll" name="chkAll" value="checkbox" onclick="checkAll('chkAll',this);" />
<input type="checkbox" name="chkSelect"   onclick="checkAll('chkAll',this);" />
<input type="checkbox" name="chkSelect"   onclick="checkAll('chkAll',this);" />
<input type="checkbox" name="chkSelect"   onclick="checkAll('chkAll',this);" />
<input type="checkbox" name="chkSelect"   onclick="checkAll('chkAll',this);" />
<input type="checkbox" name="chkSelect"   onclick="checkAll('chkAll',this);" />

<script type="text/javascript">
function checkAll(chkAllID,thisObj)
{
    var chkAll = document.getElementById(chkAllID);
    var chks = document.getElementsByTagName("input");
    var chkNo = 0;
    var selectNo = 0;
    for(var i =0; i < chks.length; i++)
    {
       if(chks[i].type == "checkbox")
       {
          //全選觸發事件  
          if(chkAll == thisObj)
          {
             chks[i].checked = thisObj.checked;             
          }          
          //非全選觸發
          else
          {
            if(chks[i].checked && chks[i].id != chkAllID)
             selectNo++;
          }
          if(chks[i].id != chkAllID)
          {
            chkNo++;
          }
       }
    } 
    if(chkAll != thisObj)
    {
        chkAll.checked = chkNo==selectNo;
    }
}
</script>
</body>


</html>


相關文章