Changing Price in Gravity Form with JavaScript Based on User Options


Gravity Forms is one of the most advanced WordPress form builders in the market today. It allows one to do complex conditional checking, not to forget complex calculations and many add-ons and support they offer.

In today’s article, I will demonstrate a step-by-step guide on how to change prices in Gravity Forms dynamically with jQuery as one selects specific options in the form.

I almost ran off the street screaming “Eureka!” when I first tried this method and it worked.

To start with, my name is Cate, a freelance coder and Mathematician(statistics) at freelancer.com. I recently got a client who wanted some complex price calculations in the Gravity Forms, something that could not have been easily achieved by Gravity Forms alone.

I was creating consultation services through Gravity Forms, a consultation service was charged per hour. For example, $x per hour for 1 to 4 hours and $y per hour for consultation above four hours.

Cost per hour was supposed to be editable in the wp-admin side independently of Gravity Forms. That too complex, we shall see how to achieve that later, for now, let’s focus on how to change price dynamically with Javascript.

Therefore, I was required to calculate the price based on the number of hours the user selected and indicate the price on the Gravity Form for users to see what they are supposed to pay.

If a user selected 3 hours, I would show the price as 3x, if the user selected 10 hours, I would change the price dynamically to 10y, that is going with the fact that $x per hour for 1 to 4 hours and $y per hour for services above 4 hours

During development, I realized many people were looking for this solution online. Unfortunately, I didn’t find the solution anywhere online, I even asked a question in StackOverflow, and until the time of writing this article, no one had answered it. The only solution you will get is overcharged add-ons that claim to solve the issue.

Well, I’m offering this for free. I will explain my approach.

I know one will ask, why offer the idea for free while you can make a Gravity Forms addon and sell? Well, a good idea, but based on the problems I  faced, and the fact that no solution was available online and considering the headaches I encountered and the number of painkillers I took, I decided to offer this for free.

Furthermore, in this blog, I offer useful programming tips for free based on my encounters in my career as a freelancer developer. I get sufficient funds through AdSense and the selling of backlinks and guest posts.

Let’s get back to the crucial business that brought us here.



Changing  Price in Gravity Forms with JavaScript/jQuery Dynamically

First, it’s worth mentioning that, you cannot just change the price of a product in Gravity Forms with javascript, it won’t gonna work.

The reason is, Gravity Forms’s product price is sent to third-party add-ons, such as Paypal or Stripe, so the price has to change in the backend too, but how? Well, we’re going to see that shortly.

Another reason why they don’t allow dynamic change of the price is that one can change prices by just editing HTML elements in the inspector tool and pay cheap, so you cannot just update product price dynamically, as a matter of fact, it’s not even possible in Gravity Forms.

Before I could realize how to do it, that was my approach but didn’t work and it rejected the amount added by JavaScript.

How to Change Price in Gravity Forms Dynamically based on user Options

Ladies and gentlemen, it’s about to happen!

It’s amazingly possible to change price dynamically with jQuery or JavaScript in Gravity Forms,  that’s changing price depending on users’ options. For example, you can have a dropdown select, when the user selects a certain option, then you update the price based on that option.

I found someone online giving a solution of having many single product fields and hiding them showing the right price at a given time. Well, that’s a long way and it’s not even possible for someone whose price calculations are complex.

For example, in my case, I had a dropdown of 20 hours, which is a select list with hours from 1 to 20.  1 to 4 hours $x per hour and above 4 hours $y per hour. You can imagine how many single products I could have created, so the idea of creating many single products couldn’t scale for my task, and it could have brought confusion.

So this was my approach:

Solution

To achieve a dynamic change of price in Gravity Forms using jQuery, I created one single product.



Remember, you cannot update the price of a single product in Gravity Forms dynamically, but we can change the quantity dynamically because the quantity is editable by the user.

So I created only one single product with a price of $ 1.00 and enabled the quantity field.

Now, I would do calculations with jQuery and update the price to the quantity field. Gravity Forms will multiply the price with quantity, remember nothing will be changed because the product’s price is 1 USD.

What do I mean? Let me give an example before showing you programmatically how to achieve that and how to make sure the quantity field is not visible to the user and users will not know what’s happening.

I will use my consultation services example to explain this.

The price of a single product is 1 dollar.

I charge $x per hour for 1 to 4 hours and $y per hour for services above 4 hours.

So if the user selected 7 hours from the select list, I would have done calculations with jQuery, and multiply that with $y which is the cost per hour for services above 4 hours. So I would have gotten 7y.

We then treat 7y as quantity and dynamically populate it to the quantity input field.

So Gravity Forms will multiply the quantity price with the price of the product, which was 1 dollar so nothing changes, the price that the user will pay will still be 7y.

Let me use real figures instead of using algebra. Let’s say we are charging 5 per hour for services above 4 hours and the user selected 7 hours. I would have used jquery and multiply 7 by 5 which is $35. That is what users should pay. Then I would treat 35 as quantity. Gravity Forms will now multiply the price of a single product with the quantity, which will be 35 by 1. which means it will return true, $35.

Now you’ve gotten the clue. The main issue now is to make sure the user doesn’t see the quantity field and real price of the product which is $ 1.00. We shall be showing the user only the calculated price by jQuery, which will end up being the price because if quantity multiplied by 1, it will not change anything.

At the front end, all you need is to inject an HTML that will cover the real product and its quantity, then make sure the background color is the same.

Please do not hide the single product; if you hide it, then it will be ignored by Gravity Forms, and users will not be charged. We shall put some div on top of the real price and cover it up with a higher z-index.

So we shall inspect the HTML with the browser inspector tool. We shall get the parent of the single product element; let’s say, for example, the parent of the single product has an Id of field_13_19. We shall make sure this field is positioned relative so that we can inject an HTML and position it absolutely to that field.

#field_13_19{
  position: relative !important;
}

Above is the CSS of the parent of the real product along with its price of 1 dollar and quantity input.

This is how to inject an HTML that will cover that field. Remember, the Gravity Forms is not rendered immediately, so if you write a jQuery code to inject HTML, you have to create a timer to delay the injection to wait for the form to be rendered.

We shall inject code inside #field_13_19 with a div which will have a class of g_custom_display_price___

<script>
  jQuery(function(){
    inject_price_display_code();
  });

  function inject_price_display_code(){
    var time = 0; 
    function real_time__(){
      var id = setTimeout( real_time__, 1000 ); 
      if( time == 2 ){
        jQuery( '#field_13_19' ).append('<div class="g_custom_display_price___"><strong>Fees</strong><br />Price: <span>$ 1.00</span></div>')
        
        clearTimeout( id );
      }
      
      time ++;
    }

    real_time__();

  }
</script>

As you may see from the above code, we have waited for 2 seconds after the page loads to inject our HTML. In most cases, 2 seconds is enough; the form will have rendered.

What we did, we appended a div inside the parent of the real product. Now that will just append it, but it will not cover the real price and quantity.

Before we see how to cover the real price, we have added this div '<div class="g_custom_display_price___"><strong>Fees</strong><br />Price: <span>$ 1.00</span></div>

.You can replace Fees by the name of the label that you gave your single product in the Gravity Forms during form creation. Also, $ 1.00 is the default price. That’s where we shall be adding our price, while the real price will be behind this div, so it will not be visible. $ 1.00 will be updated by our jQuery.

Now, remember we positioned the parent #field_13_19 relative. Now, to cover the real price and quantity, add this CSS code.

.g_custom_display_price___{
    background: #FFF;
    width: 100%; 
    height: 100%;
    position: absolute; 
    z-index: 9; 
    top: 0; 
    bottom: 0;
    paddig-right: 5px;
    color: #000;
  }

  .g_custom_display_price___ span{
    color: #1884bf !important;
  }

AS you can see, the div has been positioned absolutely with a z-index of 9, and it will be 100% the height and width of the relatively positioned element, which in our case is the parent element of the real price.

To make sure the whole thing looks professional, make sure the background of the cover div is the same as the background of the form. Also, you can change the price colors and so on.

Now we can update our quantity without the user seeing it and display the price on the new div. The displayed price will not be used anywhere; it just shows users what they are expected to pay.

Now let’s assume the input of quantity has an id of #ginput_quantity_13_19. This is how to do calculations with jQuery



<script>
  jQuery( function(){
    intelligent_price_calculator();
  } );

  function intelligent_price_calculator(){
    var above_four_hours = 7; // cost per hour for services above 4 hours
        var one_to_four_hours_price = 4; // cost per hour for 1 to 4 hours
        var hours = jQuery("#input_13_36").val();
        var total = 0; 

        // on loading the page
        if( parseInt( hours ) <= 4 ){
        	total =  parseInt( hours ) * parseInt( one_to_four_hours_price ); 
        } else {
        	total =  parseInt( hours ) * parseInt( above_four_hours ); 
        }

        jQuery( '#ginput_quantity_13_19' ).val( total );
        jQuery( '.g_custom_display_price___ span' ).html( "$ "+total+".00" );


        jQuery("body").on( 'change', '#input_13_36', function(){
        	// on changing the hours selection
        	var hours_ = jQuery(this).val();

        	if( parseInt( hours_ ) <= 4 ){
          	total_ =  parseInt( hours_ ) * parseInt( one_to_four_hours_price ); 
          } else {
          	total_ =  parseInt( hours_ ) * parseInt( above_four_hours ); 
          }
        	jQuery( '#ginput_quantity_13_19' ).val( total_ );
        	jQuery( '.g_custom_display_price___ span' ).html( "$ "+total_+".00" );
        } );

        //input_13_38


        jQuery("body").on( 'change', '#input_13_38', function(){
        	// on selecting Yes/No
        	var hours__ = jQuery( "#input_13_36" ).val();

        	if( parseInt( hours__ ) <= 4 ){
          	total__ =  parseInt( hours__ ) * parseInt( one_to_four_hours_price ); 
          } else {
          	total__ =  parseInt( hours__ ) * parseInt( above_four_hours ); 
          }
        	jQuery( '#ginput_quantity_13_19' ).val( total__ );
        	jQuery( '.g_custom_display_price___ span' ).html( "$ "+total__+".00" );
        } );


  }
</script>

.Ignore everything else and focus on this:

jQuery( '#ginput_quantity_13_19' ).val( total );

jQuery( '.g_custom_display_price___ span' ).html( "$ "+total+".00" );

As you can see, we are populating quantity filed with total and displaying to the users the total they are expected to pay.

If you would like to hire me for your Gravity Forms complex coding or create a Gravity Forms addon or create custom code that extends normal Gravity Forms usage. you can email me at catekhui30@gmail.com

Happy coding!

AdBlock Detected!
This site depends on revenue from ad impressions to survive. If you find this site valuable, please consider disabling your ad blocker or pausing Adblock for this website.