Limiting Selections

Where you only want one entry out of a group to be able to be selected you can use radio buttons. What can you do though where you need to allow more than one to be selected but have an upper limit on how many can be selected. The only option in that situation is to use check boxes and to apply a test afterwards to ensure that the maximum number of selections hasn't been exceeded. Here' we will look at how we can add some JavaScript to test this limit so as to advise immediately if they try to select too many without waiting for the form to be submitted.

This latest version of my limited checkbox selection JavaScript removes all of the processing from the HTML and handles everything from the JavaScript. To use the script you just need to have all of the checkboxes belonging to a particular group enclosed in an element with a specific id. You then call the limitSel() function with the id of that group as the first parameter, the maximum number of selections as the second parameter, and the error message to display if that limit is exceeded and the last selection automatically unselected again as the third parameter.

Let's take a look at a simple working example of this:

Please select up to 2 boxes and 3 hats.
Message:
Boxes: 1 2 3 4 5
Hats: 1 2 3 4

Now here's the script that you attach to the bottom of any page where you want to limit selections.

JavaScript

Next you make sure that your form contains somewhere to display the error message. The code I usually use looks like this:

<fieldset><legend>Message:<'/legend>
<div id="message"></div>
</fieldset>

We also need to make sure that the checkboxes are grouped together in a way that the script can identify them. In my example I have done this by wrapping all the checkboxes in a group within a fieldset and giving that fieldset an id.

All that remains to be added is the call(s) to limitSel() to limit the selections in your form. As the fieldset defining my 'boxes' group has an id of 'boxes' and we only want to allow two checkboxes in this group to be selected we call the function like this:

limitSel('boxes',2,'Please choose only 2 box checkboxes.');

 

This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow
Donate