Simon John Hd
Simon John Hd

Reputation: 25

Gravity Form - get field values and sum only if field value is 1

I have 4 number fields on gravity form User can input values between 1 to 5 I want to count how many values are 1 and sum up total.

So for e.g.

Field 1 = 1
Field 2 = 4
Field 3 = 5
Field 4 = 1

Then total no. of 1 are 2 (Field 1 + Field 4)

How can i make this work to gravity form?

Upvotes: 0

Views: 1628

Answers (1)

Dave from Gravity Wiz
Dave from Gravity Wiz

Reputation: 2869

Here's a working form export your can import and play around with.

Download Form Export

The pertinent code (inside the HTML block):

<script type="text/javascript">
jQuery( document ).ready( function( $ ) {

    var $inputs = $( '#input_1484_1, #input_1484_2, #input_1484_3' ),
        $sumInput = $( '#input_1484_4' );

    $inputs.change( function() {

        var oneSum = 0;

        $inputs.each( function() {
            if( parseInt( $( this ).val() ) === 1 ) {
                oneSum += parseInt( $( this ).val() );
            }
        } );

        $sumInput.val( oneSum );

    } );

} );
</script>

To implement this on your own form, you will need to:

  • Update the $inputs variable with the input HTML IDs for each Number field you wish to include in the calculation.
  • Update the $sumInput variable with the input HTML ID of the Number field in which you would like to sum the number of 1-value fields.

Upvotes: 1

Related Questions