spivurno
9/12/2012 - 6:12 PM

Gravity Wiz // Limit How Many Checkboxes Can Be Checked

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));