I first wrote about selecting all of the checkboxes in an ASP.NET ListView almost three months ago now. You may of noticed in my last post some cleaner code to achieve this that doesn’t require adding arbitrary classes or id’s for hooks. Since I didn’t point it out, I thought I would share it as well as my first jQuery plugin that does the same thing with a few more extras.
Screenshot of End Product:
So to start, the code that I am using now to select of all of the CheckBoxes in the first column of a table:
Once the document is ready, selectors are used to find the first CheckBox in the head of the table and then a click event is added to it. When the CheckBox is clicked its checked status is added to the variable checkedStatus. Next selectors find the CheckBox in the first cell of each column in the body of the table. Then each is used to iterate through this wrapped set and the checked status of each CheckBox is set to the value stored in checkedStatus.
The nice part about the code above is that the only client id you have to worry about is for the table itself. If you use MasterPages or Panels or anything that messes with the client id in ASP.NET you won’t have to track them down or add extra classes to your markup to be able to get your code working.
Since I use this on almost all of my tables I thought I would try turning it into my first jQuery plugin. One of the things that came to mind when building the plugin was what if I didn’t want the column of CheckBoxes as the first column? How could I support this? Turns out it was pretty easy to setup my defaults for the plugin to look for the CheckBoxes in the first column, but provide options that allow for the CheckBoxes to be in whatever table column the user designates. I also ended up adding default tooltips to the CheckBox in the head that can be overridden as well. So without any further verbiage:
To call the plugin, you just have to select your table and then add “.selectAllRows();” See the demo, for examples (with code) that show using different columns and overridden tooltips.
There is other stuff that could be done to improve this plugin. I have been working on adding a callback that will allow for things like disabling or enabling items on the contextMenu plugin I use or whatever you want to do once the CheckBoxes have all been checked or un-checked. Its working, but not that well yet. I will update you when it does. If your interested in building your own plugins I recommend checking out the documents on the jQuery web site or the chapter on building plugins in the book jQuery in Action.
Let me know in the comments what you think and what could be improved.