Created
September 12, 2012 18:12
-
-
Save spivurno/3708752 to your computer and use it in GitHub Desktop.
Gravity Wiz // Limit How Many Checkboxes Can Be Checked
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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