[JavaScript]GridView上CheckBox全選某欄 使用javascript的作法

  • 12203
  • 0
  • 2009-01-05

使用javascript,將某Gridview上特定欄的checkbox全選

 

js的部分,主要的function為SelectAll(),其餘部分僅為了與ScriptManager相容。

備註1:GridView上有RowCommand可能會影響到js的cell.childNodes的深度

備註2:尚未補上當列上checkbox打勾時,檢查是否連動全選的checkbox

備註3:尚未檢查是否checkbox為唯讀


Java Script

function SelectAll(checkboxid,Gridid) {          
    var grid = __GetID(Gridid);         
    var cell;            
    if (grid.rows.length > 0)
    {           
        for (i=1; i<grid.rows.length; i++)
        {           
            cell = grid.rows[i].cells[0];
           
            for (j=0; j<cell.childNodes.length; j++)
            {           
                if (cell.childNodes[j].type =="checkbox")
                {
                    cell.childNodes[j].checked = __GetID(checkboxid).checked;
                }
            }
        }
    }
}

function __GetID(vstrID){
    if (typeof(Sys) !== "undefined"){
        return $get(vstrID);
    }
    else {
        return document.getElementById(vstrID);
    }
   
}

if (typeof(Sys) !== "undefined") Sys.Application.notifyScriptLoaded();


C#

protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        //grid header上的全選Checkbox=CheckBox1
        CheckBox CheckBox1= (CheckBox)e.Row.FindControl("CheckBox1");
        if (e.Row.RowType == DataControlRowType.Header)
        {
            //全選的功能
            CheckBox1.Attributes["onclick"] = "SelectAll('"+CheckBox1.ClientID+"','"+ GridView1.ClientID+"')";
        }
    }

 

補充(2009/1/5):特定欄checkbox全選的作法,僅補充javascript,C#部分多一個參數為ColumnIndex即可。

function SelectAllCheckBox_Column(id,Gridid,ColumnIndex) {          
    var grid = document.getElementById(Gridid);          
    var cell;            
    if (grid.rows.length > 0)
    {            
        for (i=1; i<grid.rows.length; i++)
        {  
            cell = grid.rows[i].cells[ColumnIndex];
            if (cell != null)
            {
                for (j=0; j<cell.childNodes.length; j++)
                {            
                    if (cell.childNodes[j].type =="checkbox")
                    {
                        cell.childNodes[j].checked = document.getElementById(id).checked;
                    }

                }

            }

        }

    }

}

blog 與課程更新內容,請前往新站位置:http://tdd.best/