How to Calculate Fields and Set Values Using JavaScript in Dynamics 365

How to Calculate Fields and Set Values Using JavaScript in Dynamics 365

JavaScript is one of the most powerful customization tools available in Microsoft Dynamics 365. It allows developers to automate calculations, populate fields, validate data, set default values, and improve user experience directly on forms.

Using the Dynamics 365 Client API, developers can retrieve field values using getValue() and update fields using setValue(). These methods are commonly used for real-time calculations and business logic execution.

In this article, we will learn how to calculate fields and automatically set values using JavaScript in Dynamics 365.

Why Use JavaScript for Field Calculations?

Common business requirements include:

Workflow:

User Updates Field → JavaScript Triggered → Calculation Performed → Value Updated → Form Refreshed

Understanding Form Context

Modern Dynamics 365 JavaScript uses:

var formContext =
executionContext.getFormContext();

Form Context provides access to:

Microsoft recommends using formContext rather than older Xrm.Page methods.

Getting Field Values

Syntax:

formContext
.getAttribute("fieldname")
.getValue();

Example:

var quantity =
formContext
.getAttribute("new_quantity")
.getValue();

The getValue() method retrieves the current value of a column on the form.

Setting Field Values

Syntax:

formContext
.getAttribute("fieldname")
.setValue(value);

Example:

formContext
.getAttribute("new_status")
.setValue("Approved");

The setValue() method is used to update field values programmatically.

Example 1: Calculate Total Amount

Fields:

JavaScript:

function calculateTotal(executionContext){

    var formContext =
    executionContext.getFormContext();

    var quantity =
    formContext.getAttribute("new_quantity")
    .getValue();

    var unitPrice =
    formContext.getAttribute("new_unitprice")
    .getValue();

    if(quantity && unitPrice){

        var total =
        quantity * unitPrice;

        formContext
        .getAttribute("new_totalamount")
        .setValue(total);
    }
}

Output:

10 × 500 = 5000

Example 2: Calculate Age

Fields:

JavaScript:

function calculateAge(executionContext){

    var formContext =
    executionContext.getFormContext();

    var dob =
    formContext.getAttribute("new_dob")
    .getValue();

    if(dob){

        var today =
        new Date();

        var age =
        today.getFullYear() -
        dob.getFullYear();

        formContext
        .getAttribute("new_age")
        .setValue(age);
    }
}

Result:

DOB: 01-Jan-2000
Age: 25

Example 3: Set Default Value

Requirement:

Status = New

JavaScript:

function setDefaultValue(executionContext){

    var formContext =
    executionContext.getFormContext();

    formContext
    .getAttribute("new_status")
    .setValue("New");
}

Default values can be assigned automatically during form load.

Example 4: Calculate Days Between Dates

Fields:

JavaScript:

function calculateDays(executionContext){

    var formContext =
    executionContext.getFormContext();

    var startDate =
    formContext.getAttribute("new_startdate")
    .getValue();

    var endDate =
    formContext.getAttribute("new_enddate")
    .getValue();

    if(startDate && endDate){

        var diff =
        endDate - startDate;

        var days =
        diff / (1000*60*60*24);

        formContext
        .getAttribute("new_duration")
        .setValue(days);
    }
}

Output:

01-Jan-2025
↓
31-Jan-2025
↓
30 Days

Example 5: Set Lookup Value

Lookup fields require:

Dynamics 365 lookup values must be passed as an array containing id, name, and entityType information.

JavaScript:

var lookupValue = [];

lookupValue[0] = {
    id:"{GUID}",
    name:"CRMONCE",
    entityType:"account"
};

formContext
.getAttribute("parentcustomerid")
.setValue(lookupValue);

Result:

Lookup Automatically Populated

Example 6: Calculate Percentage

Fields:

JavaScript:

function calculatePercentage(executionContext){

    var formContext =
    executionContext.getFormContext();

    var obtained =
    formContext.getAttribute("new_obtained")
    .getValue();

    var total =
    formContext.getAttribute("new_total")
    .getValue();

    if(obtained && total){

        var percentage =
        (obtained / total) * 100;

        formContext
        .getAttribute("new_percentage")
        .setValue(percentage);
    }
}

Output:

450 / 500 = 90%

Registering JavaScript

Navigate:

Solution → Web Resources → JavaScript File

Upload:

calculate.js

Add to Form:

Form Properties → Add Library → Add Event

Events:

OnChange Event Example

Field:

Quantity

Event:

OnChange
↓
Calculate Total

Workflow:

User Changes Quantity → JavaScript Executes → Total Updated

Real-World Example

Sales Order Calculation

Fields:

Workflow:

Enter Quantity → Enter Unit Price → Calculate Discount → Calculate Total → Update Form

Result:

Automated Pricing

Common JavaScript Functions

Get Value

getValue()

Set Value

setValue()

Show Notification

setFormNotification()

Hide Field

setVisible(false)

Disable Field

setDisabled(true)

Get Control

getControl()

These Client API methods are commonly used in Dynamics 365 form scripting.

Best Practices

Use Form Context

Avoid deprecated methods.

Handle Null Values

Always check for blanks.

Use OnChange Events

Reduce unnecessary processing.

Keep Code Modular

Create reusable functions.

Test Across Forms

Verify behavior in Create and Update modes.

Use Meaningful Names

Common Challenges

Null Values

Field is empty.

Wrong Schema Name

JavaScript cannot find the field. Incorrect schema names often cause getAttribute() to return null.

Lookup Errors

Missing GUID or entity type.

Event Not Registered

Function never executes.

Benefits

Better User Experience

Instant calculations.

Improved Accuracy

Reduce manual errors.

Faster Data Entry

Auto-populate fields.

Automated Business Logic

Real-time execution.

Increased Productivity

Less manual effort.

Workflow Summary

User Action → JavaScript Event → Get Field Value → Perform Calculation → Set New Value → Save Record

Conclusion

JavaScript plays a critical role in Dynamics 365 customization by enabling real-time calculations and automatic field updates. Using getValue() and setValue(), developers can retrieve data, perform calculations, populate fields, validate input, and enhance the overall user experience.

Whether you're calculating totals, percentages, durations, ages, or setting lookup values, JavaScript provides a flexible and powerful approach to implementing business logic directly within Dynamics 365 forms.