Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Gravity Wiz // Gravity Forms // Checkbox Count
<?php
/**
* --------------------------------------------------------------------------
* IMPORTANT!
* This snippet has been superceded by the Choice Counter snippet.
* https://gist.github.com/spivurno/00af5ee7e21dd5d6903fbae6fecd85ce
* --------------------------------------------------------------------------
*
* Gravity Wiz // Gravity Forms // Checkbox Count
*
* Get the total number of checkboxes checked. Useful when wanting to apply conditional logic based on the number of
* checkboxes checked.
*
* @version 2.5
* @author David Smith <david@gravitywiz.com>
* @license GPL-2.0+
* @link http://gravitywiz.com/...
* @copyright 2018 Gravity Wiz
*/
class GW_Checkbox_Count {
private static $is_script_output;
function __construct( $args ) {
$this->_args = wp_parse_args( $args, array(
'form_id' => false,
'count_field_id' => false,
'checkbox_field_id' => null,
'checkbox_field_ids' => false
) );
if( isset( $this->_args['checkbox_field_id'] ) ) {
$this->_args['checkbox_field_ids'] = array( $this->_args['checkbox_field_id'] );
}
add_filter( 'gform_pre_render', array( $this, 'load_form_script' ), 10, 2 );
add_action( 'gform_register_init_scripts', array( $this, 'add_init_script' ) );
//add_action( 'gform_pre_validation', array( $this, 'override_submitted_value') );
}
public function load_form_script( $form, $is_ajax_enabled ) {
if( $this->is_applicable_form( $form ) && ! has_action( 'wp_footer', array( $this, 'output_script' ) ) ) {
add_action( 'wp_footer', array( $this, 'output_script' ) );
add_action( 'gform_preview_footer', array( $this, 'output_script' ) );
}
return $form;
}
function output_script() {
?>
<script type="text/javascript">
( function( $ ) {
window.GWCheckboxCount = function( args ) {
var self = this;
// copy all args to current object: formId, fieldId
for( prop in args ) {
if( args.hasOwnProperty( prop ) )
self[prop] = args[prop];
}
self.init = function() {
for( var i = 0; i < self.checkboxFieldIds.length; i++ ) {
var checkboxFieldId = self.checkboxFieldIds[ i ],
checkboxField = $( '#input_' + self.formId + '_' + checkboxFieldId );
checkboxField.find( 'input[type="checkbox"]' ).click( function() {
self.updateCheckboxCount( self.formId, self.checkboxFieldIds, self.countFieldId );
} );
}
self.updateCheckboxCount( self.formId, self.checkboxFieldIds, self.countFieldId );
};
self.updateCheckboxCount = function( formId, checkboxFieldIds, countFieldId ) {
var countField = $( '#input_' + formId + '_' + countFieldId ),
count = 0;
for( var i = 0; i < checkboxFieldIds.length; i++ ) {
var checkboxField = $( '#input_' + formId + '_' + checkboxFieldIds[ i ] );
count += checkboxField.find( 'input[type="checkbox"]' ).filter(':checked').not(' #choice_' + checkboxFieldIds[ i ] + '_select_all').length;
}
if( parseInt( countField.val() ) != parseInt( count ) ) {
countField.val( count ).change();
}
};
self.init();
}
} )( jQuery );
</script>
<?php
self::$is_script_output = true;
}
function add_init_script( $form ) {
if( ! $this->is_applicable_form( $form['id'] ) )
return;
$args = array(
'formId' => $this->_args['form_id'],
'countFieldId' => $this->_args['count_field_id'],
'checkboxFieldIds' => $this->_args['checkbox_field_ids']
);
$script = 'new GWCheckboxCount( ' . json_encode( $args ) . ' );';
$slug = implode( '_', array( 'gw_checkbox_count', $this->_args['form_id'], $this->_args['count_field_id'] ) );
GFFormDisplay::add_init_script( $this->_args['form_id'], $slug, GFFormDisplay::ON_PAGE_RENDER, $script );
return;
}
function override_submitted_value( $form ) {
//$_POST["input_{$this->count_field_id}"] = $day_count;
return $form;
}
public function is_applicable_form( $form ) {
$form_id = isset( $form['id'] ) ? $form['id'] : $form;
return empty( $this->_args['form_id'] ) || $form_id == $this->_args['form_id'];
}
public function is_ajax_submission( $form_id, $is_ajax_enabled ) {
return isset( GFFormDisplay::$submission[ $form_id ] ) && $is_ajax_enabled;
}
}
# Configuration
new GW_Checkbox_Count( array(
'form_id' => 123, // the ID of your form
'count_field_id' => 2, // any Number field on your form in which the number of checked checkboxes should be dynamically populated; you can configure conditional logic based on the value of this field.
'checkbox_field_ids' => array( 5, 8 ) // any array of Checkbox field IDs which should be counted
) );
@ghost

This comment has been minimized.

Copy link

ghost commented Jan 16, 2018

Unreal. This is exactly what I need right now.

What’s the best way to retrieve the value from this function on my thank you page? At the moment, users are redirected after form submission.

Thanks so much, David!

:)

@Nab59

This comment has been minimized.

Copy link

Nab59 commented Jan 28, 2018

Hello,
I was looking for this function since 1 week, so i am very happy :-)

Can you tell me how to use it please ?
Regards

@UnionDesign

This comment has been minimized.

Copy link

UnionDesign commented Feb 9, 2018

This saved my live. Thank you. Really needs to make it into the core. The conditional logic options in GF are really limited.

@cassihl

This comment has been minimized.

Copy link

cassihl commented May 3, 2018

I added the code and changed the IDs in the configuration section, I get these errors:

Uncaught ReferenceError: GWCheckboxCount is not defined
at HTMLDocument. ((index):642)
at HTMLDocument.dispatch (jquery.js?ver=1.12.4:3)
at HTMLDocument.r.handle (jquery.js?ver=1.12.4:3)
at Object.trigger (jquery.js?ver=1.12.4:3)
at Object.a.event.trigger (jquery-migrate.min.js?ver=1.4.1:2)
at HTMLDocument. (jquery.js?ver=1.12.4:3)
at Function.each (jquery.js?ver=1.12.4:2)
at a.fn.init.each (jquery.js?ver=1.12.4:2)
at a.fn.init.trigger (jquery.js?ver=1.12.4:3)
at HTMLDocument. ((index):642)

Can you help me figure out why?

Thanks!

@adamthomson

This comment has been minimized.

Copy link

adamthomson commented May 23, 2018

This was the perfect solution after weeks of pulling my hair out. Thanks so much.

@jandreaucodes

This comment has been minimized.

Copy link

jandreaucodes commented Aug 28, 2018

Is there any solution if you’re using the “Select All” option?

If you use that, you’ll have an extra checkbox counted.

For example, if I have 5 checkboxes and someone checks the Select All checkbox, the count is actually 6. The 5 checkboxes, plus the Select All one.

@ryeradio

This comment has been minimized.

Copy link

ryeradio commented Oct 8, 2018

I have this added to my functions file, but what do I do after that? Should there be an added function/field to get this to work in the gravity forms? Do I add a number field and some sort of a count function?

@mgwaters

This comment has been minimized.

Copy link

mgwaters commented Oct 27, 2019

This worked great for me, and my selected checkbox values are making it all the way to the order confirmation emails.

Is it possible to tie the value of a checkbox:

example: [ name="input_29.1" id="choice_2_29_1"] item #1 check box

and have that determine which digital download file to grant access to for a particular product?
http://prntscr.com/potmrf

Appreciate any guidance on this. Thank you!

@spivurno

This comment has been minimized.

Copy link
Owner Author

spivurno commented Oct 28, 2019

This worked great for me, and my selected checkbox values are making it all the way to the order confirmation emails.

Is it possible to tie the value of a checkbox:

example: [ name="input_29.1" id="choice_2_29_1"] item #1 check box

and have that determine which digital download file to grant access to for a particular product?
http://prntscr.com/potmrf

Appreciate any guidance on this. Thank you!

Seems feasible but that'd be more on the WooCommerce side of things. I don't have a ready solution for this one.

@drmzeeshan

This comment has been minimized.

Copy link

drmzeeshan commented Jan 29, 2020

This snippet helped me a lot. Thats exactly what I was looking for. How I used the code:
Step 1: Added a text field in my form (noted down its ID for later use)
Step 2: Set it to receive dynamic value by checking "Allow field to be populated dynamically" in Advanced tab
Step 3: Noted down all the checkbox field IDs from where I want to count the checkboxes
Step 4: Installed "Code Snippets" plugin.
Step 5: Added a new snippet and copy pasted the above code by @spivurno in it
Step 6: At the end of code there is configuration area. Set it. Set the form id. Set the text filed ID (from step 1). Set the checkbox ids from step 3.
In the end just saved the snippet and enabled it. Thats it. The newly created text field should start receiving live updates of checkbox count.

And now I need a tweak in this process.
Instead of receiving the updates in the text field I want to receive the data outside of gravity form. I need to display the checkbox count in the Header or Footer of the webpage.
Is there a way to target some other gravity form and send updates to that other form's text field ID?
Please help.
Thank you

@spivurno

This comment has been minimized.

Copy link
Owner Author

spivurno commented Jan 29, 2020

@drmzeeshan If you target the change event of the input being populated with the checkbox count, you can then set the value of the other element by ID like so:

$( "#input_123_4" ).change(function() {
    $( '#other_form_input' ).val( $( this ).val() )  
});
@drmzeeshan

This comment has been minimized.

Copy link

drmzeeshan commented Jan 29, 2020

@drmzeeshan If you target the change event of the input being populated with the checkbox count, you can then set the value of the other element by ID like so:

$( "#input_123_4" ).change(function() {
    $( '#other_form_input' ).val( $( this ).val() )  
});

I am trying to understand your solution. I am sure it will work but sorry I am a newbie. Have to figure this out.
Please let me know where to put the code you provided? In some function in the original code? or in some new file?

This is the information I have, which I think will help you understand what I am talking about:

DATA ORIGINATING FORM:
Form ID which has the checkboxes fields: 1
Checkbox fields IDs: 15, 21, 25, 30, 35, 40

DATA RECEIVING FORM:
Form ID which needs to receive the checkbox count: 3
Text box field ID of the receiving form: 1

And this is the configuration settings in your original code:

new GW_Checkbox_Count( array(
'form_id' => 1,
'count_field_id' => 52,
'checkbox_field_ids' => array( 15, 21, 25, 30, 35, 40 )
) );

Thank you

@spivurno

This comment has been minimized.

Copy link
Owner Author

spivurno commented Jan 29, 2020

@drmzeeshan I wish I could provide pro bono support but my plate is full! If you're a Gravity Perks customer, we'll be happy to take a look via support.

@drmzeeshan

This comment has been minimized.

Copy link

drmzeeshan commented Jan 29, 2020

@drmzeeshan I wish I could provide pro bono support but my plate is full! If you're a Gravity Perks customer, we'll be happy to take a look via support.

Thank you for what you have already provided.
Just one thing. May you please point me towards some documentation which can address this issue. Some relevant material to read.
I will then try my best to understand it and solve this issue. I really need to sort this issue out.
Thanks

@spivurno

This comment has been minimized.

Copy link
Owner Author

spivurno commented Jan 30, 2020

@drmzeeshan I don't have a great resource to direct you to that is specific to this use-case; however, you might consider posting on the Gravity Forms Community Forum: https://community.gravityforms.com/

@drmzeeshan

This comment has been minimized.

Copy link

drmzeeshan commented Jan 31, 2020

Hello David @spivurno
After spending tons of hours finally I figured it out.
Its JQuery syntax. I learned the language from youtube tutorials. (Not completely of course but enough to understand the basic concepts).
Then inside your method:
self.updateCheckboxCount = function( formId, checkboxFieldIds, countFieldId )
and inside the If clause: if( parseInt( countField.val() ) != parseInt( count ) )
I added this simple piece of code:
$( "#input_3_1" ).val( count ).change();
Hard coded the form id and field id. LOL. But it worked.

thank you so much for your basic code otherwise of course I couldn't have created it on my own.

Just one last question, if you may pleas reply:
Is it possible to target some other webpage element like this? I mean anything to target other than gravityform elements. I am now thinking to target populate a simple html text field. (It makes it lot easy to customize the look and feel of simple html elements. For me setting up looks and griding of gravity form is very hard).

Thanks

@spivurno

This comment has been minimized.

Copy link
Owner Author

spivurno commented Jan 31, 2020

@drmzeeshan Just update this bit to target any element on the page. jQuery is not limited to Gravity Forms. It can access any element. 🙂

$( "#any_element_id" ).val( count ).change();
@mrhat7865

This comment has been minimized.

Copy link

mrhat7865 commented Mar 30, 2020

Hi, thanks so much for this useful code, how can this be adapted to count the number of selections made in a gravity form multi-select?

@spivurno

This comment has been minimized.

Copy link
Owner Author

spivurno commented Mar 30, 2020

@mrhat7865 You'd need to update line 90 to target options instead of inputs and then if they're selected rather than checked.

We'd be happy to assist with this if you're a Pro Gravity Perks license-holder: http://gravitywiz.com/

@lavalldesign

This comment has been minimized.

Copy link

lavalldesign commented Apr 8, 2020

How do you use it? I'm not sure.

I think I'm following all the steps but I don't know how to report the value

Thank you

@spivurno

This comment has been minimized.

Copy link
Owner Author

spivurno commented Apr 8, 2020

@lavelldesign Make sure you're setting the count_field_id to a field on your form. If you need more assistance, we do offer support for our snippets to our Gravity Perks customers (Pro and Advanced).

http://gravitywiz.com/support/

@lavalldesign

This comment has been minimized.

Copy link

lavalldesign commented Apr 16, 2020

@spivurno. FANTASTIC!!!!!!!!

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.