Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gravity Wiz // Limit How Many Checkboxes Can Be Checked
<?php
/**
* Limit How Many Checkboxes Can Be Checked
* http://gravitywiz.com/2012/06/11/limiting-how-many-checkboxes-can-be-checked/
*/
class GFLimitCheckboxes {
public static $field_limits;
function __construct($form_id, $field_limits) {
$this->field_limits = $field_limits;
add_filter("gform_pre_render_$form_id", array(&$this, 'pre_render'));
}
function pre_render($form) {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$.fn.checkboxLimit = function(n) {
var checkboxes = this;
this.toggleDisable = function() {
// if we have reached or exceeded the limit, disable all other checkboxes
if(this.filter(':checked').length >= n) {
var unchecked = this.not(':checked');
unchecked.prop('disabled', true);
}
// if we are below the limit, make sure all checkboxes are available
else {
this.prop('disabled', false);
}
}
// when form is rendered, toggle disable
checkboxes.bind('gform_post_render', checkboxes.toggleDisable());
// when checkbox is clicked, toggle disable
checkboxes.click(function(event) {
checkboxes.toggleDisable();
// if we are equal to or below the limit, the field should be checked
return checkboxes.filter(':checked').length <= n;
});
}
});
</script>
<?php
foreach($form['fields'] as $field) {
if(!array_key_exists($field['id'], $this->field_limits) || RGFormsModel::get_input_type($field) != 'checkbox')
continue;
$script .= "jQuery(\"#field_{$form['id']}_{$field['id']} .gfield_checkbox input:checkbox\").checkboxLimit({$this->field_limits[$field['id']]});";
}
GFFormDisplay::add_init_script($form['id'], 'limit_checkboxes', GFFormDisplay::ON_PAGE_RENDER, $script);
return $form;
}
}
new GFLimitCheckboxes(115, array(5 => 2));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.