Calculate the Value of a field using JavaScript

Here is a simple way to calculate the value of a field based on the values of two other fields on a form using JavaScript.  The value of the field is updated whenever the value of one of the two other fields is changed.
For this example, I will use the Opportunity form.  The request is to add a custom field that shows the Total Value of the Opportunity after Discount.  I will use the following fields for reference in the example.
  • Field1 (Custom attribute) = Total_Estimated_Value
  • Field2 (Custom attribute)  = Total_Discount
  • Field3 (Standard attribute)= Est. Booking (estimatedvalue)
Steps to implement the change:
  • Create the two custom attributes that you need by going to Settings, Customization, Customize Entities, open the Opportunity Entity, select Attributes, create two new money attributes, and save the changes.
  • Open the Opportunity form and add the two fields to the form.
  • Double-click (Open) the Est. Booking field (estimatedvalue) on the form and add the following line of script to the OnChange event of the field
    crmForm.all. Total_Estimated_Value.FireOnChange();
  • Open the Total_Discount field on the form and add the same script to the OnChange event of the field
  • Open the Total_Estimated_Value field on the form and add the following script to the OnChange event of the field
    crmForm.all.Total_Estimated_Value.DataValue=crmForm.all.estimatedvalue.DataValue – crmForm.all.Total_Discount.DataValue
  • Save your changes and test using the Create or Update Form feature from the Customization Tool

The end result will be that whenever the Total_Discount or Est. Booking field is updated the Total_Estimated_Value will update by subtracting the Total_Discount from the Est. Booking amount.

Please note that this example assumes there is always a value in the Est. Booking and Discount field when one of those fields are updated.  You may have to add some additional code that first checks to see if there is a value in the Total_Discount and Est. Booking field before firing the “crmForm.all.Total_Estimated_Value.FireOnChange();” script.  If there is no value (null), then you will have to set the value to 0 (zero).  Checking and setting the default value of the fields to 0 can be done in the Form properties OnLoad event.

One comment

  1. Thanks for this wonderful post. I definitely like the content you put up on your web page. Added to my bookmarks for future visits.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s