Simple 'Select-all' checkbox javascript for ASP.NET GridView, DataList, Repeater etc

One of the most common scenarios encountered in webpages is that of checkbox lists. I have seen many javascript implementations to handle selection/deselection of checkboxes in GridView like scenarios. In this article, I suggest yet another method to handle this scenario. Two big advantages of this method are:

  • No need to deal with “ClientIds” of ASP.NET controls. The javascript is independent of Ids of individual controls.
  • No extra code needs to added to ‘code-behind’ (*.aspx.cs). I mean absolutely no need for attaching javascript to individual checkboxes from code-behind.

In this article,I will illustrate the use of this method for checkbox column of a GridView. We will use jQuery javascript library for this, as future versions of Visual Studio are going to support it. So here we go: Firstly, add a ‘template column’ to a GridView. In the header and footer template we add a checkbox. Set the CSSClass of the checkbox in header and item template to ‘chkHeader’ and ‘chkItem’ , respectively. It is not necessary to define these styles.

Then, we add our javascript to the page. Be sure to include jQuery script file, before the script.

<script src="jquery-1.2.6.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(window).bind('load',function(){
var headerChk = $(".chkHeader input");
var itemChk = $(".chkItem input");
headerChk.bind("click",function(){
itemChk.each(function(){this.checked = headerChk\[0\].checked;})
});
itemChk.bind("click",function(){if($(this).checked==false)headerChk\[0\].checked =false;});
});
</script>

Now run the page.Selecting and deselecting the header checkbox should also change checkbox in each row. Deselecting checkbox from any row, should deselect the header checkbox. As, you must have realized you can apply similar technique for DataList, Repeaters and other such scenarios. Also this method is not ASP.NET specific, it should work for any scenario.