L

ist collector variables are a great way (currently the only way) to allow a user to select multiple options from a referenced table in a single variable on a service catalog item. The list collector variable allows you to choose from one to many (potentially hundreds or more) selections. What if you wanted to limit the number of items that a user could select? This script does exactly that. It restricts the selected items list on a list collector variable to whatever amount you choose. Just use the catalog client script below and set the variables for the maximum number of selections and the name of the variable to apply the restriction to.


Limit Selections Catalog Client Script
Name: Limit Selections
Type: onChange
UI type: Desktop
Script:

function onChange(control, oldValue, newValue, isLoading) {
    //Limit the number of selected options in a list collector
    //Specify the max options and variable name below
    var maxOptions = 5;
    var varName = 'users';
    var leftBucket = gel(varName + '_select_0');
    var rightBucket = gel(varName + '_select_1');
    var selectedOptions = rightBucket.options;
    if(selectedOptions.length > maxOptions){
        //Move any options with IDs greater than maxOptions back to left bucket
        var selectedIDs = [];
        var index = 0;
        for(var i = maxOptions; i < selectedOptions.length; i++){
            selectedIDs[index] = i;
            index++;
        }
        //Move options and sort the left bucket
        moveSelectedOptions(selectedIDs, rightBucket, leftBucket, '--None--');
        sortSelect(leftBucket);
        alert('You cannot select more than ' + maxOptions + ' options.');
    }
}

Service Portal version

With the introduction of the Service Portal UI, ServiceNow severely limits the client-side API that is available. That, in addition to the completely different UI of the list collector element itself, requires a different scripting approach. The following script is designed to work as a client script in Service Portal ONLY. Just make sure you change the ‘UI type’ field to ‘Mobile’ for this script.

Limit Selections Catalog Client Script (Service Portal version)
Name: Limit Selections
Type: onChange
UI type: Mobile
Script:

function onChange(control, oldValue, newValue, isLoading) {
    //Limit the number of selected options in a list collector
    //Specify the max options and variable name below
    var maxOptions = 5;
    var collectorName = 'users';
    var myListCollector = g_list.get(collectorName);
    var selectedOptions = g_form.getValue(collectorName).split(',');
    if(selectedOptions.length > maxOptions){
        //Remove the last item
        myListCollector.removeItem(selectedOptions[selectedOptions.length-1]);
        g_form.addErrorMessage('You cannot select more than ' + maxOptions + ' options.');
    }
}