Skip to content

Instantly share code, notes, and snippets.

@chrisegg
Created October 17, 2023 01:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisegg/1a3599e901982808c2607bf75728f589 to your computer and use it in GitHub Desktop.
Save chrisegg/1a3599e901982808c2607bf75728f589 to your computer and use it in GitHub Desktop.
This snippet allows you to limit the number of checkboxes that can be checked, and grays out and disables all other choices when that number is reached.
/**
* GravityRanger Limit Checkboxes
*
* This snippet allows you to limit the number of checkboxes that can be checked, and grays out and disables all other choices when that number is reached.
*
*
* @instructions:
*
* 1. Change 2 on line 24 to the number of checkbox choices you want the user to be able to select.
* 2. Change the 1_5 on line 27 to the formID_fieldID of your checkbox field.
* 3. Add the scipt to an HTML field within your form or use a code snippet plugin.
*
* @version 1.0
* @author GravityRanger
* @license GPL-2.0+
* @link http://gravityranger.com/
*
*
*/
<script>
jQuery(document).ready(function($) {
var maxCheckboxes = 2; // Change this to your desired maximum number of checkboxes.
// Replace "input_1_5" with the ID of your checkbox field. You can find it in the Gravity Forms settings.
var checkboxField = $('#input_1_5 input[type="checkbox"]');
checkboxField.on('change', function() {
var checkedCheckboxes = checkboxField.filter(':checked');
if (checkedCheckboxes.length >= maxCheckboxes) {
// Disable and grey out all other checkboxes.
checkboxField.not(':checked').prop('disabled', true).closest('label').css('color', '#999');
} else {
// Re-enable all checkboxes when the limit is not reached.
checkboxField.prop('disabled', false).closest('label').css('color', '');
}
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment