Checking All Checkboxes in a GridView Using jQuery
In May 2006 I wrote two articles that showed how to add a column of checkboxes to a GridView and offer the ability for users to check (or uncheck) all checkboxes in
the column with a single click of the mouse. The first article, Checking All CheckBoxes in a GridView,
showed how to add "Check All" and "Uncheck All" buttons to the page above the GridView that, when clicked, checked or unchecked all of the checkboxes. The second article,
Checking All CheckBoxes in a GridView Using Client-Side Script and a Check All CheckBox, detailed how
to add a checkbox to the checkbox column in the grid's header row that would check or uncheck all checkboxes in the column. Both articles showed how to implement such
functionality on the client-side, thereby removing the need for a postback.
The JavaScript presented in these two previous articles still works, but the techniques used are a bit antiquated and hamfisted given the advances made in JavaScript
programming over the past few years. For instance, the script presented in the previous articles uses server-side code in the GridView's DataBound event
handler to assign a client-side onclick event handler to each checkbox. While this works, it violates the tenets of unobtrusive
JavaScript, which is a design guideline for JavaScript programming that encourages a clean separation of functionality from presentation. (Ideally, event handlers
for HTML elements are defined in script.) Also, the quantity of JavaScript used in the two previous articles is quite hefty compared to the amount of code that would
be needed using modern JavaScript libraries like jQuery.
This article presents updated JavaScript for checking (and unchecking) all checkboxes within a GridView. The two examples from the previous articles - checking/unchecking
all checkboxes using a button and checking/unchecking all checkboxes using a checkbox in the header row - are reimplemented here using jQuery and unobtrusive
JavaScript techniques. Read on to learn more!
Read More >