Check all checkboxes in Gridview using jQuery

Many blog has been already written on it, and thinking this I never come with my this old content. Someone ping me to post it at my blog as he often refer it, and he said it will be easier for him. Smile

Well, Checking/un-checking all row checkboxes on header checkbox checked and checking to header checkbox when user checked to all row level checkboxes can be done easily and in many ways. The idea is to find the header checkbox and check if it has been checked, and accordingly all Gridview's row level checkboxes is set.

So, lets find header checkbox using jQuery with ID selector-

$("[id$=HeaderCheckBox]")  ;

But, it will search into all DOM items for ID HeaderCheckBox. So, instead of searching the whole DOM, lets come with some specific search range to get some better performance.

$("input:checkbox[id$=HeaderCheckBox]")  ;

This one is quite better than first one. It is defining the search range and instead of taking whole DOM for lookup.

Well, it is goog because we have placed single checkbox in header row of our gridview. If we talk about row level item findings, we should come with different finding approach used for list or group name based items. For example, one row of our Gridveiw may contains option for choosing gender with help of radio button list or it may contain multiple checkbox value selection inside a row. Also, we know that list controls gets rendered differently if there is master pages and other wrapper controls are present, so we need to handle it. In this case, generally, control’s IDs get generated like below-

ctl00_cphName_RowCheckBox_0
ctl00_cphName_RowCheckBox_1
ctl00_cphName_RowCheckBox_2 and so on...

Thus, we can see group-name based selector can works as an effective selector because our control’s ID is coming differently and ending with numbers.

$('input:checkbox[name$=RowCheckBox]')  ;

so, far we have got good selector to find our elements or items on DOM. Now it is time to apply our logic. And, the entire code can be written as - 

$(function(){

// Handle your header checkbox Click 
  $("[id$=HeaderCheckBox]").click(function () { 
     $("input:checkbox[name$=RowCheckBox]").attr('checked', this.checked); 
  }); 

// Handle invidual checkbox click 
  $("[id$=RowCheckBox]").click(function(){
     if($("input:checkbox[name$=RowCheckBox]").length == $("input:checkbox[name$=RowCheckBox]:checked").length) 
        $("[id$=HeaderCheckBox]").attr('checked', "checked"); 
     else 
         $("[id$=HeaderChecBox]").removeAttr("checked"); 
  });

});//end of jQuery ready fn

Happy coding Secret telling smile