1 min read

Visualforce Select All/None with Prototype JS

A common use-case that I implement over and over is to provide the user with a multi-select table of records that the user can select and process. This typically includes a Select All/None option.

Related List Screenshot

I originally wrote this functionality using an action function tag that would run a method on the controller. The method would loop through the list of records and mark each record as selected or unselected before returning the results as a post-back. The solution worked but it was very slow and seemed really unnecessary to have to submit the form to the server just to select a bunch of checkboxes.

To solve for this I used a JavaScript implementation that provided the same functionality client-side. To make my life easier I chose to include the Prototype JS library on my page. Prototype has a very convenient selector method that can select elements in a number of ways. To use this library you will need to download the latest version and add it to your static resources. Then you can include it on the page using the <apex:includeScript> tag.

Here is an example of the JavaScript that will select all checkboxes with a class name of “rowSelect”. The class name is not important, the only requirement is that the class name is only used by the checkboxes you want to support with the select all feature.

function toggleSelectAll(selectAll) {
    var elArray = $$(‘input.rowSelect’);
    elArray.each(function(item) {item.checked = selectAll;});
}

As you can see it is a pretty simple JavaScript function and it is much faster than using a post-back or AJAX call.