Limiting How Many Checkboxes Can Be Checked
A simple method for limiting how many checkboxes can be checked (and how many checkboxes must be checked) on a checkbox field.
February 9, 2013: Updated to only apply validation on currently submitted page for multi-page forms.
Stop! There's a better way.
This snippet is available as a plugin with Gravity Perks, a suite of over 46 premium Gravity Forms plugins!
The snippet might look daunting but it only requires a quick copy and paste and two simple configurations to get it up and running!
How do I install this snippet?
Just copy and paste the code into your theme’s functions.php file.
Do I need to modify this snippet to work with my form?
This snippet now uses a class format. This means you can more easily use it on multiple forms! To instantiate this class you will need to know the form ID, field ID and minimum/maximum number of checkboxes which should be allowed/enforced for that field. It will look something like this:
new GFLimitCheckboxes(123, array(
5 => array(
'min' => 2,
'max' => 3,
),
));
In template form:
new GFLimitCheckboxes(FORM_ID, array(
FIELD_ID => array(
'min' => MIN_NUMBER,
'max' => MAX_NUMBER,
),
));
You can specify multiple checkbox fields on a specific form like so:
new GFLimitCheckboxes(123, array(
5 => array(
'min' => 2,
'max' => 3,
),
13 => array(
'max' => 3,
),
));
Finally, you can apply this functionality to multiple forms:
new GFLimitCheckboxes(123, array(
5 => array(
'min' => 2,
'max' => 3,
),
13 => array(
'max' => 3,
),
));
new GFLimitCheckboxes(321, array(
1 => array(
'max' => 4,
),
));
And that’s it!
You can use a little CSS to style the labels for the disabled checkboxes. Here is an example where I’ve set the color to gray: input[type="checkbox"]:disabled + label { color: #999; }
Will this work with Gravity forms 2.7.2 & multiple fields? The order of the code doesn’t seem to matter. Whatever the first field is on the displayed form, works fine, then the following fields behave as if nothing was written for them.
Tested with GF 2.7.2 and multiple fields â both min and max limits were honored for both fields.
If you’re a Gravity Perks customer, you might consider using the perk version of this, GP Limit Checkboxes or contacting support for a deeper dive if you need to use this snippet version for some reason.
Is it possible to limit the options of a selector with populate anything?
Hi Carlos,
If I understand correctly, you want to set the number of options that populates a dropdown field? If so then you can use this gppa_query_limit filter hook to set the number of values that are returned when using GP Populate Anything. You can use the last example on the hook documentation that targets a specific field on a form to do what you want. If this isn’t what you want and I have misunderstood your question, please let us know. You can get in touch with us via our support form.
Best,
Samuel! Hello! No, I don’t want to limit the number of queries, but I do want to limit the number that can be selected once the query brings me the options.
Hi Carlos,
We have a Perk version of this functionality, GP Limit Checkboxes Perk, that should work when using GP Populate Anything. Please check it out.
Best,
Hello Samuel, I have tried that Perk. It works ok with checkboxes, but not with the Selector module. Is it possible to implement it in selector? Thank you!
Hi Carlos,
What exactly is a selector module? If you have an active Gravity Perks license, can you get in touch with us via our support form and send an export of the form, so we can take a look at the setup and assist you further?
Best,
Samuel!
this module: https://docs.gravityforms.com/multi-select/
Hi Carlos,
The Snippet and Perk don’t work on a Multi-Select field. We do, however, have a Javascript snippet you can use to limit selection on a Multi-Select Field.
https://github.com/gravitywiz/snippet-library/blob/master/gravity-forms/gw-limit-multiselect.js
Check out the snippet page for more details on how to use it and give it a try.
I hope this helps.
Best,
Samuel!!!! I solved it!!!
http://snippi.com/s/faxzsjg
Hi Carlos,
Glad you were also able to find a solution that works for you.
Best,
Samuel! It is possible that the snippet does not work in mobile?
Hi Carlos,
Yes, I can confirm the snippet currently doesn’t work on mobile. I’m forwarding this to our developers to look into this and see if mobile support can be added to the snippet. One of our developers will update this comment with an update on this.
Best,
Hi Carlos,
The snippet has been updated and it works now on mobile devices.
Best,
Hi Samuel,
Thnx for the code! Works fine, I just want to know how to apply more form IDs and more field IDs in the code? Now I make the same code for each field. And also want to use the code for more more forms.
This didn’t work:
26,28,29 => array( ‘min’ => 2, ‘max’ => 2 )
The code how it was used for 1 form with the same settings for all fields.
new GFLimitCheckboxes(2, array( 26 => array( ‘min’ => 2, ‘max’ => 2 ), 28 => array( ‘min’ => 2, ‘max’ => 2 ), 29 => array( ‘min’ => 2, ‘max’ => 2 ) ));
Hi Tim,
This will require some adaptation to the snippet. If you have an active Gravity Perks license, please get in touch through our support form, and we’ll dig into it.
Another option would be migrating to Limit Checkboxes perk.
Best,
Just wondering where the form ID and field ID need to be put in the code? The image attachments to git hub dont work.
Hi Jeremy,
The configuration is at the button of the code, similar to this;
new GFLimitCheckboxes(115, array( 5 => array( 'min' => 2, 'max' => 3 ), 13 => array( 'max' => 3 ) ));
The form ID in the code above is 115 and the field IDs are 5 and 13.
Hi Samuel,
Thanks for replying, I tried the below as I only have one check box that needs the code however doesn’t seem to be working.
new GFLimitCheckboxes(4, array( 135 => array( ‘min’ => 2, ‘max’ => 3 ) ));
Hi Jeremy,
I just did a test using your configuration, by just changing the Form and Field IDs and it worked, so it’s strange it’s not working for you. Does it display any error message? You may want to try it again but instead of copying and pasting, type the configuration part of the code. If you have an active Gravity Perks license you can get in touch with us via our support form and we’ll be happy to look into this further.
Best,
Hi Samuel
It works! I was using a code plugin and forgot to activate the snippet!
Thanks for the help.
Hi folks,
Wondering if you can help, but appreciate it’s outside the remit – the snippet works perfectly for me if you’re logged in but doesn’t seem to work for logged out users. Any idea why that might be?
I’m getting a jQuery error: .checkboxLimit is not a function in the console when the form loads in while in incognito that doesn’t appear when signed in. I see elsewhere you were asking about page builders – the site uses Elementor.
Thanks for any insights!
This appears to have resolved itself – I think we were overcaching our JS. Thanks anyway!
Hi Mel,
Yes, this is often a caching-related issue. Glad you were able to get it working.
Best,
Does not work. Code snippet plugin throes error “Uncaught Error: Class “GFLimitCheckboxes” not found in ………/public_html/wp-content/plugins/code-snippets/php/admin-menus/class-edit-menu.php(248) : eval()’d code:1…….
Directly adding this snippet in functions.php causes my entire site to crash
nvm it work now
Hi Razi
Glad you were able to figure it out.
Cheers,
Is there anything similar to Multi-select?? I have a multi-select with 5 options, and I want the user to be able to ONLY choose 2 options.
Hi Haya,
We have an experimental snippet that you can use to limit a Multi-Select field.
You can use our free GF Custom Javascript plugin to add the javascript snippet to the form.
I hope this helps.
Best,
Any way to take the markings of the entire form and not of independent fields?
Hi Guillermo,
I’m not sure if I’m tracking, but if you want to span the limits across multiple fields, this is supported in the perk version of the plugin.
The snippet works great. One question is if the user clicks a box now, if they want to switch they have to un-click the current before they can switch. Is there a way to allow the user to click and have it automatically switch?
Thanks!
Thanks! Hmm, this is a good question. From what I understand as you mentioned is not currently supported. If you have a Gravity Perks license, can you get in touch with us via our support form?
Best,
I was using the code snippet, not a perk. I figured it had something to do with not disabling the other options when one is clicked?
Jonathan,
The behavior you are experiencing is by design. If you only want to let the user select one option, you can use a Radio Buttons field instead ð.
Best,
Unchecking boxes doesn’t appear to be making the other boxes enabled again in GF 2.5.16. Any ideas?
Hi Cory,
I am unable to recreate the issue on my end. Unchecking boxes is enabling disabling boxes with GF 2.5.16. If you have a Gravity Perks license, reach out via the support form so we can assist you further with this.
Works a treat for me on GF 2.5, only issue I currently have is that jQuery is throwing a console error, not entirely sure why as jQuery is loaded before this script in my functions.php
Hi Scott,
I am unable to recreate the issue on my end. It works as expected without a JQuery error. I’ll suggest you run a Theme/plugin conflict test to check if another plugin or code is causing this. If you have a Gravity Perks license you can get in touch with us via support form so we can assist you further with this.
Best,
This no longer works with Gravity Forms 2.5!
Hi Chad,
Iâm unable to recreate the issue when I test on GF 2.5. It works as expected.
We recommend purchasing the Perk version of this snippet. Not only does it offer more features and ease of use, it also includes support.
Just wondering if this code be used to set a limit for the total items checked in a combination of three fields? So limit of 5 total for Field1+Field2+Field3…
Hi Katie, not in the snippet, but spanning limits across multiple checkbox fields is available in the Perk version.
GP Limit Checkboxes
Great little piece of code but it seems to be stopping users not logged in from being able to add items to the cart (well it says they have been added but going to the cart page its empty)? The code all works as expected with the checkboxes and it works fine if you are logged in.
I removed the code and it allows me to add to cart if not logged in.
Hi Paul, I’m unable to recreate the issue. I suggest purchasing a Gravity Perks license for the GP Limit Checkboxes Perk which comes with fantastic support.
Hi,
I put the code on my functions.php and appear a fatal error. I will show you what i paste:
Estoy copiando lo siguiente: new GFLimitCheckboxes(4, array( 21 => array( ‘min’ => 1, ‘max’ => 5 ), 23 => array( ‘min’ => 1, ‘max’ => 5 ) ));
The number 4 is my ID form and the 21 and 23 is the ID field. I donÂŽt understand if apart of the gravityÂŽs plugin i need to do something else.
I suspect you may have not copied the full snippet and only the configuration. More troubleshooting steps here: https://gravitywiz.com/documentation/snippet-troubleshooting/
Thanks, worked perfectly
Glad to help, Filip!
Does the plugin support the Poll add-on and the limits can be set for the Poll field type?
Yep! It sure does. ?
Hi there! nice code :)
I see all the page but not the form.
Here is the error in chrome console: https://ibb.co/HDd1cHc
Hi Danilo, the demo is still working so there is likely a theme/plugin conflict at play.
i face the same issue. it used to be working.
Awesome snippet, thanks David!
For anyone experiencing issues: I had to make this a plugin in order for it to work. I couldn’t get it working just pasting everything in the functions.php, the code wouldn’t output the script to the page containing the form at all. I would recommend the same approach for anyone experiencing the same issue.
There may have been a formatting issue in your functions.php file but glad the plugin solution works for you. ?
Both my max fields are 3 but my form is letting 4 be picked, any idea on this?
Hi Karl, I’m not able to recreate the issue. I’d recommend picking up a copy of Gravity Perks for the GP Limit Checkboxes perk which comes with excellent support.
I’m getting a blank page using the raw code with my form/field IDs. I see this error in the log files:
PHP Parse error: syntax error, unexpected ’15’ (T_LNUMBER), expecting ‘)’ in /var/www/vhosts/curlysicecream.com/httpdocs/wp-content/themes/oceanwp-child/functions.php on line 229
Any thoughts?
This is great, but any way where I can set the limits dynamically based on the input of another field?
For example.. Since we don’t have proper checkbox products in gravity forms.. (yes I saw https://gravitywiz.com/checkbox-products-gravity-forms/, but I don’t think it’s viable when you have a few hundred options).. A person is buying and selecting seats to a concert..
How many tickets do you want to buy? (Product Dropdown: 1..10).
Results of the dropdown will limit the number of checkboxes/seats that they can select.
Let me know if it’s possible either with this snippet or with your plugin at https://gravitywiz.com/documentation/gravity-forms-limit-checkboxes/
We have a snippet that works in conjunction with our GF Limit Checkboxes perk. https://gist.github.com/spivurno/42ca347547088029b986e2b5287ccaea Happy to answer any questions.
Thanks for sharing.. this is good.. I will play with it, I see the configuration section will need to be populated with the ID’s and values..
But it seems to be related to specific values of a dropdown. What if you want a user to enter in any number (i.e. a quantity)?
Would this work for (a) spanning mutiple fields (using the Limit Checkboxes Perk) and (b) 2 different limits based for 2 different fields?
My initial testing on a site using the limit checkboxes perk, using a “Product” in the form of a dropdown doesn’t appear to be impacting.. Does the “Limit how many checkboxes can be checked” need to be enabled? If so, do we put a min/max limit, or leave blank? In the product, I tried “Show Values” using both numbers or strings like Q1, Q2, Q3, etc.. neither seemed to have an impact.. Any further documentation?
Hi Jacob, reach out to us via the support form and we’ll be happy to take a closer look at your setup. Please include an export of your form, your configuration of the conditional limits snippet and the field labels & IDs you are working with.
Thank you for supplying this. I have installed it as a plugin instead of all that code in the functions.php file.
Just created a plugin folder, dumped the code provided into an index.php file with the following header:
/* Plugin Name: Limit How Many Checkboxes Can Be Checked Plugin URI: https://gravitywiz.com/2012/06/11/limiting-how-many-checkboxes-can-be-checked/ Description: Limit How Many Checkboxes Can Be Checked Version: 0.1 */
Awesome! Thanks for sharing. :)
Awesome Bro,
Thank you so much
My pleasure, Simarjot. :)
Hi, I just stumbled onto your code and it works awesome except I have one dilemma. I have multiple field IDs being used in the same form. I added the snippet for each field ID however I need to restrict the form to max out at 15 selected checkboxes for the entire form with the combined field IDs. Is there a way to make it add together what’s taken from a separate field to combine in total for the form?
Hi Tim, spanning the limit across multiple checkbox fields is supported in GP Limit Checkboxes.
The last update for this reads, “Updated to only apply validation on currently submitted page for multi-page forms.”
What would I need to do if I wanted this to validate from any page?
Hey Greg, I’m not sure you’d ever want this. If it validates from every page, you would get validation errors on form pages that are inaccessible.
I would also recommend using the perk-version of this snippet which has been dramatically optimized.
Really a great snippet and very useful. works perfectly. Thank you
Glad to help. :)
THANK YOU for this great snippet & the introduction to Gravity Perks! For the users above who are experiencing the ‘white screen’ after copying & pasting the snippet into their functions.php, it COULD be that they are just copying one of the snippets shown on this page, such as:
new GFLimitCheckboxes(115, array( 5 => array( ‘min’ => 2, ‘max’ => 3 ) ));
RATHER than using the FULL CODE from the “DOWNLOAD CODE” button at the top of the page. The instructions within “How do I install this snippet?” do make it sound as if they only need to copy the small snippet rather than the more extensive code available within the “DOWNLOAD CODE” button.
Hope this helps someone!
Glad to help! And thanks for sharing this tip. :)
Hi David,
Really a great snippet and very useful. Few days ago I did it with javascript on front-end but this method is quite elegant. Just thinking about drop-down or multi select fields is that possible to customize this snippet to limit selection in dropdown or multiselect fields?
Hi Jamil, glad you found this snippet useful. Drop downs only allow one selection regardless. It is possible to limit multiselect fields but the code would require many changes.
Dear David, Is it possible to apply this to post categories, or product categories in the Woocommerce form? Thank you.
Not easily. You’d probably be better off with a custom solution like this.
Thanks David! The trouble with all those solutions is that they operate in the browser, which the user can change.
Wow! Thank you so much for sharing the snippet! This is going to save a lot of confusion :)
Glad to help, William. :)
I’m interested in having 15 questions, each a checkbox with one option.
Do you like scarves? as the question and a single checkbox “yes” underneath. I’ll have 15 such questions but I only want people to be able to select 8 checkboxes, i.e. select 8 yes times. Is this possible since the checkboxes are in different questions? If so, how? And do I need to buy the plugin to achieve this?
Yes, this is possible with the GP Limit Checkboxes plugin. It has a feature that allows you to span the limit over multiple files (screenshot).
Great little snippet, will come in handy.
Any chance you can help me with something? I have two separate checkbox fields, can we combine them so say no more than 7 can be checked between the two checkbox fields? Get what im saying?
Thanks -Dan
This is possible with the GP Limit Checkboxes perk. See the “Spanning limits across multiple fields” section. :)
I’ve installed the snippet to my theme’s functions, got the white screen so I did the troubleshoot and decided to just remove everything altogether but I’m still getting the white screen. Any idea on how I can get my site back? Thanks so much.
Hi J, if the site is still white screened there are three likely issues:
The snippet is not working on my end. I’ve copy and pasted the snippet into the themeâs functions.php file and configure the class at the bottom but returns an empty page.
Try troubleshooting with these steps: https://gravitywiz.com/documentation/snippet-troubleshooting/
I’ve followed how the snippet should be pasted in the functions.php. Also, I’ve modified the class below according to the form and field ID I am using and it makes the page empty.
And you’ve done all the steps in the “Digging Deeper” section?
Thank you so much!!! I am so glad I found this. I am at the point where I can do advanced customizations, but I don’t write code. I am slowly teaching myself by patching in other code like this.
Glad we could help, Jessica! Keep learning. ;)
Works like a charm! Thanks
Hi David,
This looks like a very useful snippet. I added the code to my functions.php file.
When you talk about the class format this snippet uses, where does one make a reference to the class, is it in the Gravity form field that users the checkboxes? If so, I’m not sure which I should use. The form I’m creating is intended to be used with WooCommerce Gravity Form Addon, so to add additional fields and data when making a purchase.
I tried the different class format by copying and pasting your examples, into one of my checkbox field I want to have limitations. When I preview my form I don’t see any change. Is is possible I need to have my form on the live website to see the results?
Any clarification on how to use the class in my forms would be greatly appreciated.
Lyse
Hi Lyse, I’m not sure I understand your question. The basic premise is that you copy and paste the snippet into your theme’s functions.php file and then configure the snippet (down at the bottom) to match your form and fields as needed.
Hi David,
I realized, after writing my post, that I need to purchase the Perks bundle for this snippet to work. I’m not quite ready to justify purchasing the Perks bundle at this time.
Thank you for responding though. Lyse
Hey Lyse, this snippet does not require you to purchase the Perks bundle. It works by itself. The perk-version of this functionality provides a UI for enabling it and also a couple additional features.
Hi David, I copy-paste, without the <?php in functions.php file. Error 500… Could you give me help? i don’t understand why..
Hi Ruben, this might be helpful: https://gravitywiz.com/documentation/snippet-troubleshooting/
Hi David,
In my case, I am looking to limit the number of checkboxes selected across multiple fields. I have a form that allows users to order product samples and the checkboxes are split in multiple fields, by brand, for easier grouping and selection.
Is this possible to do with this code?
Thank you.
Hi,
I’m wondering if there is a way to set the values for MIN_NUMBER and MAX_NUMBER based on the quantity entered in a product field (ie, #ginput_quantity_2_28)?
I’m using your List field choices snippet (https://gravitywiz.com/use-list-field-choices-gravity-forms/) to populate a set of checkboxes. Now I would like to limit how many of those checkboxes can be selected according to the quantity entered in my product field.
I just don’t have the skills to figure out how to extract that quantity value and use it as my min/max when I call GFLimitCheckboxes.
Your help would be much appreciated! BTW, please let me know if that’s something that the Gravity Perks plugin can do as I would be happy to purchase that instead of asking for free help. :)
Hi Jennifer, I took a look over the code and there doesn’t appear to be a simple way to accomplish this. It’s a cool idea though. Would you be interested in commissioning me to add this feature? If so, get in touch.
Hi David, Thanks for reviewing the code for this! I’m exploring a few form options to build what we need but I’ll definitely get in touch if we decide this feature is a must have. Thanks, Jennifer
Sounds good. :)
Hi David,
First, thank you for a great snippet of code!
I’m having an issue when I use the snippet in my functions.php. When I go to save the page where the Gravity Forms shortcode is on, now I’m getting this to appear on a blank page:
Warning: Cannot modify header information – headers already sent by (output started at /home/emsco05/public_html/dev/vrdev/wp-content/themes/mobilefirst/functions.php:604) in /home/emsco05/public_html/dev/vrdev/wp-admin/post.php on line 237
Warning: Cannot modify header information – headers already sent by (output started at /home/emsco05/public_html/dev/vrdev/wp-content/themes/mobilefirst/functions.php:604) in /home/emsco05/public_html/dev/vrdev/wp-includes/pluggable.php on line 1196
line 604 starts as:
<?php endif;
It’s correlates to your php code.
Any insight as to why?
Thank you! George
Are you using a page builder plugin of any kind? Many of these fire the pre render hook but fail to capture some custom scripts output with the form block which would cause this kind of an error.
I did notice if I deactivate the plugin Relevanssi, the issue went away.
Sorry, to answer your question, I’m not using a pagebuilder plugin. However, I do have WooCommerce. The theme I’m using is a Genesis simple child theme that I have heavily customized.
Yeah, it sounds like that plugin is conflicting. I’m not able to debug plugin conflicts like this pro bono. If you’re interested in hiring me, get in touch.
Thanks David… totally understand. I appreciate the help so far!
Indeed, David this is very nice tutorial and helpful for many our developers brothers, i have also made the same tutorial but by using jQuery so that all the validation can be check on the client side. Check it out i hope you will like it too.
https://htmlcssphptutorial.wordpress.com/2015/07/01/jquery-checkbox-validation-limiting-checkboxes-to-be-checked/
Good stuff, Javed. Thanks for sharing. :)
Thanks bro :)
Amazing, just copy/paste in functions.php, use your parameters in GFLimitCheckboxes, and perhaps translate the validation messages, and it works like a spell ! If you only have a minimum constraint however, you need to set the maximum parameter to a very big number, in order to avoid the “undefined number” condition. Thank you for sharing !
Glad you like it! The only easier way to install and use this functionality (plus the bonus feature of being able to share the limit across multiple checkbox fields) is the perk-version: GP Limit Checkboxes.
Does this snippet work with GF 1.9 that was just released (1/28/15)? Just tried it in functions.php and it doesn’t seem to do anything.
Thanks,
Rob
Actually, sorry â it does work! PHP’s opcache wasn’t invalidating functions.php on the server and picking up the new changes. :)
Thanks for your work.
Rob
I was browsing the internet to find out how to limit the number of checkboxes with Gravity Forms. This code is awesome and works flawlessly. Thanks for sharing it and I hope you have a great day.
Susan
Hi,
I’m using your code along with Gravity Forms Addon plugin for woocomerce.
I have a product with variations, that once a variation is selected the gf form appears and lets me choose product features. Is there any way to set different limitations to same gf field based on the variation selected?
Thanks
Hi Asaf, this is not possible without additional custom code. It is possible immediately if you didn’t need it to apply to the same field.
Thanks,
Can you provide a code example?
Hi Asaf, here is a tutorial on populating drop down fields. The same concept applies to any multiple choice field (i.e. radio, checkbox, drop downs). With this you can control which choices show up on a field. Don’t want a field to show up based on the current date? Just don’t include it when generating the choices.
http://www.gravityhelp.com/documentation/page/Dynamically_Populating_Drop_Down_Fields
It’s not really what I need. I need some kind of condition in your code that will have 2 cases: 1. Variation A => limit selection for 2 choices 2. Variation B => limit selection for 4 choices
The example you gave me deals with weather to show/not show selections
Ah, yes, I confused myself. There really is no simple code example I can provide that demonstrates how to accomplish this. Are you unable to use multiple fields with different checkbox limits and show/hide the appropriate field based on conditional logic?
LoL :)
I’d rather use same fields with limitation conditions, however if this can’t be done, how can I create a conditional logic that shows filed 1 for woocommerce variation A, and filed 2 for woocommerce variation B?
GF conditional logic are based on GF fields only, right? There’s a way around it – using GF product flied, but I want to use WOO product options.
Ah, I did not realize the variations were on the WC product. Assumed you were talking about a Gravity Forms product + options. So this would required two levels of customization:
Typically, I would love to tackle a small customization like this but I’m a little booked up at the moment. Give Codeable.io a try. They specialize in small customizations.
Thanks
Asaf, I’ve run into the exact same situation that you discussed with David. I’m curious if you had any luck getting this figured out.
Thanks so much for taking the time to respond!
~ Brandon
Great! Does this plugin also work with the wp-admin? For example the category box in posts?
Best regards!
Sorry Razz, this only works for forms powered by Gravity Forms.
This is great! Thanks for your help.
I personally would suggest making the checkbox feel more like a radio button, as that’s what most users , at least in my mind and personally, would interact with the checkboxes if they must be selected at a max of ‘1’.
I understand it’s probably a better idea to use Radio Buttons if that’s the case on my end, but my project specifically requires a checkbox. This of course is a hack to a hack, so… I can’t ask for too much, eh?
Thanks again.
Hi Aaron, thanks for the feedback. Using a checkbox field with a max of “1” is a strange requirement. Can you share more details on the reasoning?
Specifically David, The radio button option for PayPal Payments Pro auto-calculates and de-calculates based on user interaction.
I agree with my client that it is a bit confusing, therefore I specifically chose to use Checkboxes.
Works beautifully, thanks David!
Glad you found this useful, John! Hope all is well. :)
I was curious if there is additional code that could be added to this to limit check-boxes across multiple fields? As an example, If i had 3 separate check-box fields, “vegetables, pastas & risottos” You could only choose 1 option from all three fields. Any help is appreciated.
Hi Tony, this is supported in “perk” version of this snippet (available with Gravity Perks). You can read more about it here.
Hi David,
First, thanks for all the snippets – some very useful looking stuff that I hope to use in the future.
Sorry if these are stupid questions (and no reason at all for you to reply) but:
1) Could this be easily customized to check for the number of checked selections in more than 1 select box? 2) Could the limit be set either by selecting a product quantity field, or passed as a variable?
Thanks either way, as I said I really appreciate what you’ve posted here and elsewhere.
Cheers
Bob
Hey Bob, the GP Limit Checkboxes perk (based on this snippet) provides the ability to span the limit across multiple checkbox fields.
Setting the limit via a product quantity field or passed as a variable is possible with some custom work. Get in touch with me if you’d like to discuss this further. :)
hello, just a small question where can i put this validation in our system? in our validate form?
Hi Toshihiro, this would go your in your theme’s functions.php or a snippet manager plugin (like this one).
What an excellent code snippet!!! Worked great!
Thanks for the praise, Justin! You might be interested to know this functionality (with a per field UI and other enhancements) is available with Gravity Perks. Even easier to install and configure and includes automatic upgrades to always ensure compatibility with the latest version of Gravity Forms.
I’m late to the game but for anyone like me (knows enough to be dangerous and crash sites) if you add this to your funtions.php and it dose not work or crashes just at the ?> before the starting <?php of this code.
Is it possible to apply this code to the Multi-Select field type? Or does it only work for checkboxes?
Only checkboxes, Aleks.
Hi, I’m using this code (GFLimitCheckboxes) for long time – it’s great! But now I need limit checkboxes for specyfic post ID. Could You help me? Best regards! Eve
Hi Eve, to clarify, do you mean that you want to change the limit on a specific form depending on which post it is embedded in?
Exactly. I have: new GFLimitCheckboxes(23, array( 77 => array( ‘min’ => 1, ‘max’ => 3 ), 85 => array( ‘min’ => 1, ‘max’ => 3 ) ));
and for specyfic post ID I need change ‘max’ parameter from 3 to 5. But only for this one post.
Best regards!
David, this is the first time I have used Gravity forms and your snippet has just made it absolutely fit for purpose for my clients needs. Many thanks for taking the time to explain the process out. Tim
Thanks for the praise, Tim. It is much appreciated.
Thank you for this code, it was exactly what I was looking for. Is there an easy way to make the word selections more grayed out after the limit of checkboxes has been reached instead of just disabling the checkboxes?
Thanks again, Kris Rhoades
Hi Chris, this is possible with a little CSS:
input[type="checkbox"]:disabled + label { color: #999; }
. Just paste that in your theme’s stylesheet. More information available here.Hey David,
Thanks so much for the fantastic snippet! It works great on the current form I’m working on, but I noticed a jQuery conflict in my situation.
My form is multi-page and utilizes Ajax, and when the Next page button is pressed, a “jQuery is not defined” error is logged. I’m guessing the (document).ready aspect is being called multiple times, but everything seems to be working regardless.
Not sure if it’s a huge issue, but any ideas how to get around this? Thanks in advance
I’m not sure what to do after I copy the code specified into my theme’s function.php. Then what? I’m obviously missing something. I’d really like to get this to work.
Thanks!
Hi Susan, check out the “Do I need to modify this snippet to work with my form?” section in the article above. It provides some examples of how this snippet can be initialized to work with your form. Let me know if you have any questions based on those examples.
Hi there, this looks like an awesome snippet even when I have tried your demo. However it seems very close to what I want to achieve.
You have asked for a description or scenario where we need more than one filed to be triggered with this.
Scenario:
We are requiring some feedback from students on a scale of 1-6 on usability of 6 personas for the survey.
I have created 6 sets of number fields labeled for different personas. I have limited the number field of a range 1-6.
However I want that the user can only choose 1 number for the ranking of the 6 personas, and not use a number that has been chosen.
persona 1 : rank order of importance 1-6 persona 2 : rank order of importance 1-6 persona 3 : rank order of importance 1-6 persona 4 : rank order of importance 1-6 persona 5 : rank order of importance 1-6 persona 6 : rank order of importance 1-6
If they choose persona 1 has importance of 2, then the number 2 cannot be used for the other 5 personas in this ranking survey form.
Hopefully this explains the scenario of what I would like to achieve.
Regards,
Ciaran
I copied & pasted as-is, and I’m getting this error:
Parse error: syntax error, unexpected ‘”‘ in themes/Avada/functions.php on line 788
the code on that line is: $script .= “jQuery(“” . implode(‘, ‘, $selectors) . “”).checkboxLimit({$max});”;
Any ideas? Thanks.
Try copying and pasting from this raw version.
Hi David,
You could try http://wordpress.org/plugins/wp-better-emails/
I know someone who can tell me what’s going on with the formatting. They’re away for a couple of days and I’ll ask when they get back.
Cheers – glad to put back – have had some fantastic help from this site ;)
Just thought I’d let you know I can see formatting in my email notifications – ie …
something here
Cheers
Formatting didn’t show in my post – around something else there should be opening and closing paragraph tags. So the tags are showing in my email. No big deal – just thought you may like to know?
Hey thanks for letting me know Keely. I think this is how the comment notification emails work by default with WordPress? Let me know if you know otherwise.
David,
Sorry to bother you, what may help some people is letting them know that they need to add the script in the page template in order for it to work. Seems that as soon as I looked at the page source for your demo, I noticed the script there, copied it and pasted it in my page template and it worked! Now I’m going to play around with multi-forms and see how this works. I’ll let you know if I figure it out!
Thanks,
Hi Brian, you shouldn’t have to paste anything into the actual page template. If you can setup the issue you were having (prior to manually pasting the
Hey David,
Can’t seem to get this to work either. Added the php to functions.php at the bottom (removed the <?php from the top), added my form id, field id, and then my min/max. No dice. Tried in other browsers as well.
Also, the code displayed for multiple checkboxes in a form and multiple forms is exactly the same. Seems the code is basically geared towards multiple fields and not forms. Can you update this?
Thanks!
David, Another great code snippet! Is there any way we could modify the code to allow these selections to be made in the settings or somewhere on the form, instead of having to edit the code snippet every time?
Hi David Smith,
Why the demo form is not working as you mention. I did not tick any check box or tick one also can submit. Can you advise. Thanks and have nice day.
https://gravitywiz.com/demos/limit-how-many-checkboxes-can-be-checked/
Hi Ng Mun Soon, this snippet can be configured with no minimum which would allow you to submit the form with less than the maximum checked. This was how the demo was configured. I’ve updated the demo to now include a minimum as well so you can see how the validation works. :)
Splendidly brilliant David!
Thanks for all you do.
hi can anybody help me with this issue? i must tell you that i am a newbie
As the post says that it limits the number of checkboxes. i have copy and pasted the above mentioned code to functions.php but when i update the function, it comes up with blank white screen. more over my website is not opening. somehow i removed this issue but main problem of limitizing the number of checkboxes still persists.
kindly help me by defining from which line of code i should copy and past in function.php also kindly tell me at what place to paste it.
it would be helpful if you kindly identify the line of codes
Hi Hannan,
More than likely you simple do not need to include the opening <?php tag from the snippet. Try copying and pasting the snippet from here. Be sure to leave the opening <?php tag out.
This actually won’t work if you have a set of products as radio buttons. I’m starting to tear my hair out trying to figure out how to do my client’s forms using GF but client doesn’t want a shopping cart, although a shopping cart would work much better. Note to self – no more client websites – going to make WordPress themes.
Hi Keely, you are correct. This is only available for fields with the Checkbox input type.
Sorry David !
I must be too impatient … I actually tried using the github php file yesterday but that didn’t work either.
The raw version didn’t throw any errors and worked … chose 1 item and submitted and got “You must select at least 2 items.”
I then selected 2 items then got “You may only select items.”
This is the code I have at the bottom
new GFLimitCheckboxes(1, array( 40 => array( ‘min’ => 2 ) ));
So I put a max value in and now it’s this
new GFLimitCheckboxes(1, array( 40 => array( ‘min’ => 2, ‘max’ => 8 ) ));
That worked :) – there are 8 checkboxes in the field.
So it needs a max value. Just letting you know.
Thanks for pointing me to the file – much appreciated.
Hi – I’m getting an error as well …
Parse error: syntax error, unexpected ‘”‘ in functions.php on line 51 – which is line 48 in your snippet.
Would love to get this to work as I need to force 2 or more checkboxes on a field.
Thanks
I left a comment here and it has disappeared … I posted that I’m getting an error related to line 48.
Getting a developer to fix it.
Hi Keely, not disappeared, just hadn’t been approved yet. I like to make sure I answer each comment and waiting to approve them until I answer has been my only method for now. :)
With that said, if you copy and paste this snippet form the raw version I’m betting it will work. Give it a shot and let me know.
I am running into some conflicts when implementing this on a multi-page form.
(1) I get this error at the top of the form:
Warning: array_key_exists() [function.array-key-exists]: The first argument should be either a string or an integer in /home/content/a/q/u/aquaten/html/wp-content/themes/AWDMarch2011/functions.php on line 772
Line 772 is the first line in the snippet below:
(2) When I click the button at the bottom of any page to continue to the next page in the form I get a validation error. There are no errors on the page but it will not let me continue until I “fix the errors.” If I remove your script, it lets me continue without any error. Seems to be a JQuery conflict.
Here is a link to the form (the checkboxes in question appear on the last page of the form): http://www.evolutionswim.com/test
Hi Courtney, the snippet has been updated to only validate checkbox fields on the currently submitted page. This resolves your issue #2. I’m unable to recreate your first issue. I’ve sent you an email requesting more details.
Hello, Thanks for this great snippet! But I have something weird going on, when I provide the correct form id and field id I get the following error: Fatal error: Call to undefined method GFFormDisplay::add_init_script() on line 44
I have your snippet in it’s own file, then including it in my functions file.
Hi James, upgrading to the latest version (1.6.11) should resolve this issue for you.
So just wanted to check to see if this is still working, I just tried it a few different ways adding it to my functions.php, then had to close the php tag to get the page to load. It still doesn’t work. I have added it to twenty twelve as well and that doesn’t work either so shouldn’t be a theme conflict. My form id is 5 and the check box field id is 5 field after 5 is 6 so I used this new GFLimitCheckboxes(5, array( 5 => array( ‘min’ => 2, ‘max’ => 3 ), 6 => array( ‘max’ => 3 ) ));
I just copy and pasted the top section into functions.php and changed the above section to match the 5 and 6 ids.
Oh here is a pastebin of my functions.php etc http://pastebin.com/wZnaD4YZ
Never mind got it working, must have been a caching issue with firefox as I checked with chrome and IE and it worked. I was clearing cache with firefox as well but didn’t work till I closed all instances of firefox. Thanks for this.
Glad you were able to get this working. :)
Hi David, VERY useful snippet first of all, really wished it can be integrated with GF directly or make a plugin out of it.
I’m trying to apply the limitations on Multi-Select and Drop down menus, I tried your code and got an error:
Warning: array_key_exists() [function.array-key-exists]: The first argument should be either a string or an integer in /homepages/xx/dxxxxx/htdocs/site/wp-content/themes/thetheme/functions.php on line 294
My guess is the snippet will only work on Checkboxes as the title indicates? Is there a way to apply it on other selections such as the Drop down menus, multi-select, etc. (excluding Radio buttons of course)
Nevertheless, great work!
Hi FanaticWeb, this snippet will actually be a perk soon enough. :)
This wouldn’t really apply to single drop down feilds; however, I can definitely see the benefit with multi-selects. This isn’t functionality I’m intending to support for this snippet at the time but feel free to hire me if you’d like to see this snippet enhanced and shared on Gravity Wiz. :)
Thanks David! The conditional logic update works great.
How can I get this class to ignore fields that are hidden by conditional logic and aren’t necessary unless a particular value is chosen in a previous field? Like when I choose a radio button in field A I’m then presented with checkbox field B. I check the “min” amount of choices in field B and submit my form which also validates hidden checkbox fields C, D, & E, thus causing an error.
Hi Chris, I’ve just updated this snippet to support conditional logic. Let me know if you run into any issues with it.
How about support for multiple fields?
Hi! I’m trying to get this to work but seems like im doing something wrong :-l
can you help me out???
Hi Michelle, what seems to be your issue? Also, if you can provide a link to your form where this is implemented, I can check for surface-level issues. :)
Hi Dave
Thanks for the fast response. I personally need this for my online shop. The visitor can compose a gift basket. There are many different types of products in different fields. He can choose (depending on the package he bought) for example 20 different products. So it would be really cool if we could limit the checkboxes to multiple fields in a form and not just one field. I’m not sure if this is possible, it could be very difficult to write the code I think.
Cheers,
Dave
How can I limit the number of checked checkboxes to a form and not only one field?
Thank you.
I’m seeing this request pop up a bit. Could you (or any others reading this) provide an example form demonstrating a scenario where you would only want a set number of checkboxes checked across the entire form?
Hi thanks for the snippet. Like Chris said, It would be really cool if this feature could be over more than one field. That would be great.
Best regards,
Chris
Thanks for seconding this request. If it continues to be a popular request, I will definitely consider adding support for it.
Or a rule for the entire form if that isn’t possible?
To make this functionality work collectively would require significant customization to this snippet.
Ahh ok. So one couldn’t pass the parameters to all of the fields in one array to work collectively using a modified method?
Hi David,
Is there anyway the array can apply to a series of fields together as a whole instead of one by one?
For example if I have 10 checkbox fields with 4 choices in each out of the 40 checkboxes I only want the user to be able to check 1 box out of them all.
Would this work for that?
This functionality only applies to limiting checkboxes within an individual field. It can be applied to multiple fields but the limit will only apply to each field independently.
This is fantastic thanks! I’m wondering how I’d make a minimum number of selections as well? So instead of ‘pick up to 3’ it would be ‘pick exactly 3’ – no more, no less. Maybe an idea for a future snippet!
Hi Chris, this snippet has just been updated to support setting a minimum number of checkboxes which must be checked. The article has been updated to provide additional instruction for using the updated snippet.
Wow! Thanks for doing that! I’ve give it a whirl now.
Hi Jeremy,
Doesnt seem to work for me for some reason. Here is the link to my form:Â http://www.thejuicerylv.com/shop/1-case-per-week/
Not sure what the issue is. Please help. Thank you.
http://pastie.org/4400690
If you wanted to apply this to more than 1 form, could you put the
gform_pre_render_115
in an array as well? Or would you just useadd_filter('gform_pre_render_115,gform_pre_render_116','gwiz_limit_checkboxes'))
Hi Jeremy,
I’m going to be adopting a new method for most of my snippets (as required) that allows you to reuse the snippet code on multiple forms more readily. Check out the updated snippet and instructions above and let me know if you have questions. One note for you. You can apply the new snippet to multiple forms like so:
new GFLimitCheckboxes(115, array(5 => 3));>
new GFLimitCheckboxes(89, array(1 => 2));>
Awesome. I will try it now and let you know!
I just tried this out but didn’t seem to work for me. Any suggestions when this doesn’t work?
Could you provide a link to a form where you’ve implemented this? I will setup a demo form with this working now.
Hi Chris, found the issue and updated the snippet. Give it a shot. Here is a working demo:
https://gravitywiz.com/demos/limit-how-many-checkboxes-can-be-checked/