Check/Uncheck all checkboxes in asp.net by javascript

I was searching for select/deselect all checkboxes code into a gridview. I found most of them only provide to select and deselet all the checkboxes if any of the checkbox is unselected into grid the main checkbox is not affecting.

I further try to search some useful code but could not found any useful solution, some of them are selecting all the checkboxes on the page or some provides only to select and deselect but no code to deselect the main checkbox on deselecting any checkbox in grid. Let's do the complete code for it.

Here is my HTML

<asp:GridView ID="gvProducts" runat="server" AutoGenerateColumns="false">
  <Columns>
    <asp:TemplateField ItemStyle-Width="10px">
       <HeaderTemplate>
         <input type="checkbox" id="chkAll" onclick="CheckUncheck(this);" />
       </HeaderTemplate>
       <ItemTemplate>
         <asp:CheckBox ID="chkItems" runat="server" 
              onclick="ItemClicked(this,'chkAll');" />  
       </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField DataField="Product"  HeaderText="Product" />                
    <asp:BoundField DataField="Price"  HeaderText="Price" />                
    <asp:BoundField DataField="Quantity" HeaderText="Quantity"  />
  </Columns>
</asp:GridView>

Note, I added one checkbox in header with id chkAll is a html input type checkbox and other in item template for each row. I add onclick attribute and called the javascript function CheckUncheck with parameter this for header checkbox and ItemClicked with item checkbox to select and deselect the all checkbox if any checkbox in grid is unchecked.

Now let's write javascript code, add following code at the bottom of the page

<script type="text/javascript">
var TotalChekBoxes = 0;
var Counter = 0;

// Get total checkboxes only in grid and not on entire page
window.onload = function () 
{TotalChekBoxes = parseInt('<%= gvProducts.Rows.Count %>');}

function CheckUncheck(CheckBox) {
  // Get gridview control and item checkbox id
  var grid = document.getElementById('<%= this.gvProducts.ClientID %>');
  var itemCheckBox = "chkItems";  //Given ID of item checkbox

  // Get all the controls of the type INPUT into GridView.
  var Inputs = grid.getElementsByTagName("input");

  //Check/Uncheck all the checkBoxes inside the GridView.
  for (var n = 0; n < Inputs.length; ++n)
    if (Inputs[n].type == 'checkbox' 
        && Inputs[n].id.indexOf(itemCheckBox, 0) >= 0)
           Inputs[n].checked = CheckBox.checked;

  //Reset Counter
  Counter = CheckBox.checked ? TotalChekBoxes : 0; 
}

/* Function to check uncheck the all checkbox 
if any item is unchecked in grid          */
function ItemClicked(CheckBox, HCheckBox) {
  //Get Header Checkbox control.
  var HeaderCheckBox = document.getElementById(HCheckBox);

  //Modifiy Counter; 
  if (CheckBox.checked && Counter < TotalChekBoxes)
     Counter++;
  else if (Counter > 0)
    Counter--;

  //Change state of the header CheckBox.
  if (Counter < TotalChekBoxes)
     HeaderCheckBox.checked = false;
  else if (Counter == TotalChekBoxes)
     HeaderCheckBox.checked = true;
 }
</script>

This will select and de-select all the grid checkboxes on selecting/de-selecting the header checkbox. Header checkox will automatically checked or un-checked on select all the item in grid or de-selecting any item into the grid.

Ali Adravi Having 13+ years of experience in Microsoft Technologies (C#, ASP.Net, MVC and SQL Server). Worked with Metaoption LLC, for more than 9 years and still with the same company. Always ready to learn new technologies and tricks.
  • asp.net
  • javascript
By Ali Adravi On 10 Jul, 12  Viewed: 5,376

Other blogs you may like

Readonly textbox postback issues and solutions

In many cases we need to use read only text box so user cannot edit the value but readonly textbox will lost its value after postback. Let’s say you have a read only text box to set date by using ajax calendar so after post back date will be lost, other case might be you are setting some value in... By Ali Adravi   On 24 Apr 2013  Viewed: 4,219

Call code behind method from JavaScript in asp.net

There are ways to call a web service method JavaScript, for more detail you can see [how to retrieve data from database using JavaScript in asp.net][1], but is there any way to call a normal method from JavaScript? And the answer is No; show how we can call a code behind method from JavaScript,... By Jonathan King   On 08 Apr 2013  Viewed: 12,445

Gridview paginated data with search and sort functionality in asp.net

Most of the times we need to use GridView control to show tabular data in our asp.net application. We simply write procedure to search the records and bind them with GridView and show 10 to 20 records per page. Have you ever thought that why you are fetching all the records and show only 10 to 20... By Ali Adravi   On 16 Feb 2013  Viewed: 8,386

ASP.Net 4.5 new feature Model Binding

A nice feature with ASP.Net is the model binding, it reduced our code and effort to bind our well know controls like GridView, DataList, Repeater etc. So let’s see how we can bind our old controls in new and easy way. Let’s see how we bind the our grid before 4.5 1. We write the code to get... By Mike .Net   On 17 Jan 2013  Viewed: 3,200

Upload multiple image in multiple size with progress bar in asp.net

In asp.net there is not control to select multiple files and upload them once with progress bar, so we will use a small third party DLL to achieve this functionality. We will use Flajaxian FileUploader, you can download it from [http://www.flajaxian.com][1] We will create three different images... By Hamden   On 12 Jul 2012  Viewed: 6,546