Mar 11, 2012

Check all Checkbox in Gridview

JavaScript function that check or uncheck all the check-boxes of the Grid-view Data-rows depending on the state of check-box of the Grid view Header-row

<script type="text/jscript" language="javascript">
    function SelectAllCheckboxes(chkAll, chkCtrlId) {
        checked = chkAll.checked;
        elm = chkAll.form.elements;
        for (i = 0; i < elm.length; i++)
            if (elm[i].type == "checkbox" && elm[i].id.indexOf(chkCtrlId) != -1) {
                if (elm[i].checked != checked)
                    elm[i].click();
            }
    }
</script>
Add this Template-field to the Grid-view that creates check-boxes in Header-row and Data-rows and also call the above JavaScript function on the click of check-box of the Grid-view Header-row

<asp:TemplateField HeaderText="Select">
    <ItemTemplate>
        <asp:CheckBox ID="chkSelect" runat="server" />
    </ItemTemplate>
    <HeaderTemplate>
        <input id="chkAll" onclick="javascript:SelectAllCheckboxes(this, 'chkSelect');" runat="server"
            type="checkbox" />
    </HeaderTemplate>
</asp:TemplateField>

    Choose :
  • OR
  • To comment
3 comments:
Write Comments
  1. What is elm in above SelectAllCheckboxes() function.plz describe

    ReplyDelete
    Replies
    1. Here, elm is just a global variable
      In javascript, when "var" keyword is used with variable the scope of variable is local to the function, you can't access it outside the function. But without "var" it becomes global and it would be accessible globally on the page.

      Example

      //Here Scope of variable "a" is global, so you would not get error
      function f1(){
      a = 5;
      f2();
      }
      function f2() {
      alert(a);
      }

      //Here the scope of variable "a" is within function f1 only, so you would get error
      function f1(){
      var a = 5;
      }
      function f2() {
      alert(a);
      }

      Delete
    2. It is always good to declare variable with "var".
      Infact, I should have used "var" here.

      var elm = chkAll.form.elements;

      Delete