Limit number of allowed selections in Checkboxes choice

Change log
October 22, 2014
v1.1: Updated the code to support new versions of jQuery and added support for Surveys (tested in SP2010).

In this article will show you how to limit the number of allowed selections in a column of type “Choice: Checkboxes (allow multiple selections)”.

The reason for this is that a column of type “Choice: Radio Buttons”, cannot be “unselected” once it is selected.

The code gives you the ability to specify the number of options a user can select.

The script behaves differently for “single choice” and for “multi choice”.

Single: The selection “moves” when you select another option – only one “tick” is allowed
Multiple: A message appears beneath the checkboxes announcing the allowed number of selection. You cannot select another option until you have removed one of the previous selections.

IMG
The “errorText” will disappear after 4 seconds.

As always we start like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a sub site named “test” with a sub site named “English” with a document library named “Javascript”):
IMG

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

October 22, 2014: Please note that the updated code example requires jQuery verions above v1.6

Add a CEWP below your NewForm and EditForm with this code:

<script type="text/javascript" src="/Javascript/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="/Javascript/LimitSelectionsInCheckboxes.js"></script>
<script type="text/javascript">
initLimitSelections('YourFieldInternalName',2,'Only 2 selections allowed.');
</script>

Parameters explained:

FieldInternalName: FieldInternalName of your “Checkboxes-column”.
allowedSelections: Number of selections allowed.
errorText: The text shown below the checkboxes if the selections exceed the allowed number of selections. Not used if the parameter “allowedSelections” is 1.

The sourcecode for the file “LimitSelectionsInCheckboxes.js” looks like this

/* 
 * Limit allowed selections in Checkboxes-column
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * http://spjsblog.com
 * v1.1
 * LastMod: 22.10.2014
*/

var multiChoiceFields = init_multiChoiceFields();

function initLimitSelections(FieldInternalName,allowedSelections,errorText){
	if(typeof errorText === "undefined" || errorText === ""){
		errorText = "You can only select " + allowedSelections + " options.";
	}
	$(multiChoiceFields[FieldInternalName]).find("input").click(function(){
		limitSelections($(this),FieldInternalName,allowedSelections,errorText);
	});
}

function limitSelections(currOpt,fin,n,errText){
	var f = $(multiChoiceFields[fin]), c, chk;
	$("#customMultiSelectValidation").remove();
	c = f.find("input:checked").length;
	// If allowedSelections = 1 move selection
	if(n === 1){
		chk = currOpt.prop("checked");
		f.find("input:checked").each(function(){
			$(this).prop("checked",false);
		});
		currOpt.prop("checked",chk);
	}else{
		// Uncheck current selection and give user a visual feedback on number of allowed selections
		if(c > n){
			currOpt.prop("checked",false);
			f.find("td[class^='ms-formbody']").append("<div id='customMultiSelectValidation' class='ms-formvalidation'>" + errText + "</div>");
			$("#customMultiSelectValidation").fadeOut(4000)
		}
	}
}

function init_multiChoiceFields(){
	var res = {}, myMatch, disp, fin, type;
	$("td[class^='ms-formbody']").each(function(){
	myMatch = $(this).html().match(/FieldName="(.+)"\s+FieldInternalName="(.+)"\s+FieldType="(.+)"\s+/);	
		if(myMatch!=null){
			// Display name
			disp = myMatch[1];
			// FieldInternalName
			fin = myMatch[2];
			// FieldType
			type = myMatch[3];
			if(type!=='SPFieldMultiChoice'){
				return;
			}		
			// Build object
			res[fin] = this.parentNode;
			$(res[fin]).attr('FieldDispName',disp);
			$(res[fin]).attr('FieldType',type);
		}		
	});
	return res;
}

Save this code as “LimitSelectionsInCheckboxes.js” – mind the file extension, and upload to the scriptlibrary as shown above.

Ask if something is unclear.

Regards
Alexander

40 thoughts on “Limit number of allowed selections in Checkboxes choice”

  1. Hi Alexander,

    I hate to bother you but I have been trying to use your code for a couple of days now with no luck. I am hoping you can help me. I have created a document library and input the jquery and above LimitSelectionsInCheckboxes.js code. I then have a new form with a multi-select checkbox called ‘Holiday_Preferences’. I added a CEWP into my customized NewForm and input the call to the script (changing the link to point to my javascript library). Nothing happens when I click the checkboxes in my form, no errors but the script does not work either. Any help would be greatly appreciated, I am in a bind with my boss.

  2. Hi Alexander,

    Sorry to disturb you but Im a beginner in sharepoint.

    If possible, could you explain how to first implement this solution in sharepoint step by step? eg. How to create a Newform, Editpage.

    I’m currently implementing this limit checkbox selections in sharepoint, by using the standard sharepoint survey and an add-on named Kwizcom surveyplus. The clue I found was to edit the xslt file which came with the add-on.This file is for the survey questions, but I am unfamilliar with xslt.
    Is there a solution to this?

    1. Hi,
      The NewForm and EditForm is the default forms created by SharePoint for any list. The NewForm is where you first fill in the form, the EditForm is the form you use when you modify existing list items.

      This solution is made for a standard SharePoint list, and a survey has another layout. It will work in a standard survey, but will not display the “errorText”. It’s just a minor modification to make it work though.

      I have however no knowledge about this add-on so i would recommend you to test it in a standard SharePoint list or survey to verify that you get it working.

      The step-by step is just to add a CEWP below the form, add the CEWP code from the article – change the script src to your locale files and it should work.

      Take a look here for further help: How to troubleshoot when the scripts does not work

      Alexander

  3. Thanks for the reply Alexander.
    If possible, could you post a tutorial on how to limit the checkboxes in a standard sharepoint survey?
    Any help is much appreciated.

  4. Hi Alexander,
    I’ve manage to deployed your javascript in my sharepoint. Below are the scenario….
    1. i created a list with 4 column. 1 column is a “single line” type.
    2. another 2 column is a “choices’ type.
    3. When i create a “new item” and filled the second column more than 2 choices, the alert say “only 2 section allowed” appears below all other column. And it stays ther except the one below the first column.

    I only want the limit to be tagged/appeared at second column(field) only.
    Can you help me on this?

  5. Hi Alexander,

    I have a survey list, where I would like to use your script in order to limit the number of allowed checkbox selections to 2. I can make the script work on a normal custom list, but when I apply it to my survey, nothing happens.

    I have a feeling that the issue may have to do with the FieldInternalName. What is FieldInternalName in a survey? Is it the full question?

    1. Hi,
      To use this in a survey you must replace the function “init_fields()” with this one:

      function init_fields(){
      	var res = {};
      	$("td.ms-formbodysurvey").each(function(){
      	var myMatch = $(this).html().match(/FieldName="(.+)"s+FieldInternalName="(.+)"s+FieldType="(.+)"s+/);
      		if(myMatch!=null){
      			// Display name
      			var disp = myMatch[1];
      			// FieldInternalName
      			var fin = myMatch[2];
      			// FieldType
      			var type = myMatch[3];
      			if(type=='SPFieldNote'){
      				if($(this).find('script').length>0){
      					type=type+"_HTML";
      				}
      			}
      			if(type=='SPFieldLookup'){
      				if($(this).find('input').length>0){
      					type=type+"_Input";
      				}
      			}
      			// Build object
      			res[fin] = this.parentNode;
      			$(res[fin]).attr('FieldDispName',disp);
      			$(res[fin]).attr('FieldType',type);
      		}
      	});
      	return res;
      }
      

      You must also replace “ms-formbody” with “ms-formbodysurvey” in the script.

      Alexander

      1. Hi Alexander,

        Thank you so much – I got it working. It’s great.

        Can’t thank you enough.

        Now I am just struggling with how to make users reply no less than 2 times…

  6. Hi,

    I am using this company provided sharepoint site. (I don’t own this sharepoint server). I believe I have restricted access to edit certain things on this site. I don’t own the server. But to this site (internally they call it CoP) I have full control over it.

    I have created the Document library for Javascript and uploaded the jquery-1.3.2.min .

    However, I couldn’t continue with adding CEWP and how do I create the LimitSelectionsInCheckboxes.js and upload it?

    Hope u can help.

    Thanks.

  7. I am not a javascript wizard at all, and i am having some problems that it looks like others might have encountered. I followed the instructions, and it works, but the restriction of 3 selections that i set up applies to the whole survey instead of just to one column. Looks like this could have to do with the internalfieldname portion of my js file. What exactly do i need to do/where should i put the field name in the script to make this work?? Any help would be greatly appreciated- thank you!!

  8. Thank you a lot for this piece of knowledge. I’m trying to use it on SP2010Std survey. However, it’s not possible to switch CEWP to HTML source, as survey is no-ribbon list. Are there any workarounds to achieve this?
    Thank you in advance.

    1. Hi,
      I’m tidying up in old unanswered comments, and found this.
      You can achieve this by typing this in the url:
      /Lists/TheNameOfYourSurvey/NewForm.aspx?toolpaneview=2

      Alexander

  9. Dear Alexander,

    looks like I’ve found a small bug in this great script.
    I’ve managed to make it operational for SP2010 survey, but only if filed name (and that case it is question as well) consist of 1 word. Adding one more makes it non-operational.
    Test case: it was ok with question “Choice” and not ok with question “RCA Choice”.
    Although it’s not a big issue, I’d be grateful if you suggest how to resolve this.

  10. Hello,

    Could Denis or Alexander post what you did to make it functional with an SP 2010 survey. I’m looking through the code and get see why its is not working!?

    Its loading correctly and the DOM structure of the 2007 and 2010 surveys looks very similar :S

    Thanks

  11. Hello, The above script is excellent. I am also making use of SP Services cascading menus on my survey – when I insert the below script the cascading menus fail.
    I attempted to modify the above script to make it work with a survey but I was not successful. The Which_x0020_of_x0020_the_x0020_f is the internal field name of the choice check box field.
    I am also unable to update the page with a CEWP – so I added the below code to a text file – populated a CEWP onto the page and pointed it to the text file –

    1

    2

    3

    4
    initLimitSelections(‘MyCheckboxes’,2,’Only 2 selections allowed.’)
    5

    /* Limit allowed selections in Checkboxes-column

    * Created by Alexander Bautz

    * alexander.bautz@gmail.com

    * http://spjsblog.com

    * v1.0

    * LastMod: 31.12.2009

    * ———————————————

    * Requirements:

    Include reference to jquery – http://jquery.com

    * ———————————————

    *

    Call from a CEWP below NewForm and EditForm like this:

    initLimitSelections(‘MyCheckboxes’,2,’Only 2 selections allowed.’)

    */
    19

    function initLimitSelections(Which_x0020_of_x0020_the_x0020_f,allowedSelections,errorText){

    if(typeof(fields)==’undefined’){

    fields = init_fields();

    }

    if(typeof(errorText)==’undefined’ || errorText==”){

    var errorText = ‘You can only select ‘ + allowedSelections + ” options.”;

    }

    $(fields[Which_x0020_of_x0020_the_x0020_f]).find(‘input’).click(function(){

    limitSelections($(this),Which_x0020_of_x0020_the_x0020_f,allowedSelections,errorText);

    });

    }

    function limitSelections(currOpt,fin,numSel,errText){

    var mySel = $(fields[fin]);

    $(“#customMultiSelectValidation”).remove();

    // Count selections

    counter = mySel.find(‘input:checked’).length;

    // If allowedSelections==1 move selection

    if(numSel==1){

    // Remove all selections

    var currOptChecked = currOpt.attr(‘checked’);

    mySel.find(“input:checked”).each(function(){

    $(this).attr(‘checked’,false);

    });

    // Select current if checked

    currOpt.attr(‘checked’,currOptChecked);

    }else{

    // Uncheck current selection and give user a visual feedback on number of allowed selections

    if(counter > numSel){

    currOpt.attr(‘checked’,false);

    mySel.find(‘.ms-formbody’).append(“” + errText + “”);

    $(“#customMultiSelectValidation”).fadeOut(4000)

    }

    }

    }

    function init_fields(){

    var res = {};

    $(“td.ms-formbodysurvey”).each(function(){

    var myMatch = $(this).html().match(/FieldName=”(.+)”s+Which_x0020_of_x0020_the_x0020_f=”(.+)”s+FieldType=”(.+)”s+/);

    if(myMatch!=null){

    // Display name

    var disp = myMatch[1];

    // FieldInternalName

    var fin = myMatch[2];

    // FieldType

    var type = myMatch[3];

    if(type==’SPFieldNote’){

    if($(this).find(‘script’).length>0){

    type=type+”_HTML”;

    }

    }

    if(type==’SPFieldLookup’){

    if($(this).find(‘input’).length>0){

    type=type+”_Input”;

    }

    }

    // Build object

    res[fin] = this.parentNode;

    $(res[fin]).attr(‘FieldDispName’,disp);

    $(res[fin]).attr(‘FieldType’,type);

    }

    });

    return res;

    }

  12. This script (modify version) does not work on SharePoint 2010?, I used it to survey in the form of:

    /* Your Comment
    */

    function initLimitSelections(FieldInternalName,allowedSelections,errorText){
    if(typeof(fields)==’undefined’){
    fields = init_fields();
    }
    if(typeof(errorText)==’undefined’ || errorText==”){
    var errorText = ‘You can only select ‘ + allowedSelections + ” options.”;
    }
    $(fields[FieldInternalName]).find(‘input’).click(function(){
    limitSelections($(this),FieldInternalName,allowedSelections,errorText);
    });
    }

    function limitSelections(currOpt,fin,numSel,errText){
    var mySel = $(fields[fin]);
    $(“#customMultiSelectValidation”).remove();
    // Count selections
    counter = mySel.find(‘input:checked’).length;
    // If allowedSelections==1 move selection
    if(numSel==1){
    // Remove all selections
    var currOptChecked = currOpt.attr(‘checked’);
    mySel.find(“input:checked”).each(function(){
    $(this).attr(‘checked’,false);
    });
    // Select current if checked
    currOpt.attr(‘checked’,currOptChecked);
    }else{
    // Uncheck current selection and give user a visual feedback on number of allowed selections
    if(counter > numSel){
    currOpt.attr(‘checked’,false);
    mySel.find(‘.ms-formbody’).append(“” + errText + “”);
    $(“#customMultiSelectValidation”).fadeOut(4000)
    }
    }
    }

    function init_fields(){
    var res = {};
    $(“td.ms-formbodysurvey”).each(function(){
    var myMatch = $(this).html().match(/FieldName=”(.+)”s+FieldInternalName=”(.+)”s+FieldType=”(.+)”s+/);
    if(myMatch!=null){
    // Display name
    var disp = myMatch[1];
    // FieldInternalName
    var fin = myMatch[2];
    // FieldType
    var type = myMatch[3];
    if(type==’SPFieldNote’){
    if($(this).find(‘script’).length>0){
    type=type+”_HTML”;
    }
    }
    if(type==’SPFieldLookup’){
    if($(this).find(‘input’).length>0){
    type=type+”_Input”;
    }
    }
    // Build object
    res[fin] = this.parentNode;
    $(res[fin]).attr(‘FieldDispName’,disp);
    $(res[fin]).attr(‘FieldType’,type);
    }
    });
    return res;
    }

  13. Where should i define this parameters:
    FieldInternalName: FieldInternalName of your “Checkboxes-column”.
    allowedSelections: Number of selections allowed.
    errorText: The text shown below the checkboxes if the selections exceed the allowed number of selections. Not used if the parameter “allowedSelections” is 1.

    ?
    Shoudl i change smth in your code and put there names of my fields?

    1. Hi,
      Sorry for the late reply, but I have a hard time following up all the comments and emails.

      I’m glad you figured it out.

      This solution is applied only to the form you have edited. To make it global, you must add it to the master page, but I’m not sure this is a good idea as the column names and the ranges will differ.

      Alexander

  14. -Alexander can you tell me why I cannot got the result even I has do all the step that you provide. My check box list cannot be limit, currently I’m using sharepoint 2013.

  15. Hi Alexander,

    I just tried them in Moss 2007 but failed.
    I tried it in Survey but it didn’t work..
    I’m using the latest script from your site and put right ‘FieldInternalName’.
    Any idea?

  16. Awesome solution! Would this work for choice field type that is not checkboxes? I have a Multi Choice option that I am wanting to restrict to just one choice only allowed

Leave a Reply