How to Count Checkbox Selections Inside Your Form

Introduction

Would you like to count the Checkbox selections inside your form? With a small snippet, you can have your form automatically display a count of the selections that increase and decreases as each selection is made. In this tutorial, we’re going to walk you through each step on how to achieve this.

Creating the form

First, you’ll need to create a new form and add your Checkbox field to the form. If you need help in creating your form, please review this documentation.

Add a checkbox field to your form

Adding a field to hold your count of the checkbox selections

Now we’re going to add a field to your form that will contain the count as the selections are made.

We’re going to add a Single Line Text form field that will hold the count in your form.

add a single line text field to your form to hold the count of the checkbox selections

Adding the snippet to your site

Now it’s time to add the snippet to your site that will update the count as the selections are checked and unchecked.

If you need any help on adding snippets to your site, please take a look at this tutorial.

/*
 * Count checkbox selections
 *
 * @link  https://wpforms.com/developers/wpforms_frontend_output_success/ 
 */

function wpf_dev_checkbox_count() {
    ?>
    <script type="text/javascript">
		(function($) {
			
			//Count the checkbox selections on field ID 25 for the form ID 374
			var $checkboxes = $('#wpforms-374-field_25 input[type="checkbox"]');
			
			$checkboxes.change(function(){
				
				var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
				
				//Add the count to the field ID 27 for the form ID 374
				$('#wpforms-374-field_27').val(countCheckedCheckboxes);
				
			});
		})(jQuery);	
    </script>
    <?php
}
add_action( 'wpforms_wp_footer_end', 'wpf_dev_checkbox_count', 10 );

This snippet will need to have the form ID 374 to match the form ID that you’ll run this snippet for. Also in the snippet, you’ll see the field_25 and field_27 which are the field IDs that the Checkbox and Single Line Text field from the form.

If you need any help in finding your form and field IDs, please review this tutorial.

After following all these steps, as your visitors select the checkbox selections, the count will update.

now you can see the count of the checkboxes changes as they are made

And that’s all you need! Would you like to use Smart Tags for your checkbox labels? Take a look at our tutorial on How to Process Smart Tags in Checkbox Labels.

Action Reference: wpforms_wp_footer_end