Home › Dynamics 365 Customer Engagement (CRM) › Adding an OnChange Script Programmatically in Dynamics 365 Power Apps
Dynamics 365 Customer Engagement (CRM) · May 3, 2018

Adding an OnChange Script Programmatically in Dynamics 365 Power Apps

In this post, we will look at how to programmatically add an OnChange script in Dynamics 365 Power Apps, so when a user tabs off a field, the script is run.

First, when we tab off a field, such as this fax field on the account record, we would like our script to run:

Without doing this programmatically, we would select the field and select Change Properties:

Then go to Events and select the OnChange event and add a new script:

Easy enough. But let’s do it programmatically instead. We will use addOnChange:

formContext.getAttribute(arg).addOnChange(myFunction)

The code. Let’s register 3 functions to run. We can see that we can easily do this:

[sourcecode language=”JavaScript”]
function RunOnLoad(executionContext) {
var formContext = executionContext.getFormContext();
formContext.getAttribute("fax").addOnChange(HelloWorld);
formContext.getAttribute("fax").addOnChange(HelloWorld2);
formContext.getAttribute("fax").addOnChange(HelloWorld3);
}

function HelloWorld(executionContext) {
console.log("Hello World");
}

function HelloWorld2(executionContext) {
console.log("Hello World 2");
}

function HelloWorld3(executionContext) {
console.log("Hello World 3");
}

[/sourcecode]

Let’s register this on OnLoad of the form and pass the executionContext as the first parameter:

Go into Dev Tools on the browser, and we see all 3 change scripts have run:

 

One Response to Adding an OnChange Script Programmatically in Dynamics 365 Power Apps

  1. What happens if you call addOnChange multiple times for the same function? For example:

    fld.addOnChange(function () { ShowHideSection(formContext) }); // gets called 4 times

    Will it call ShowHideSection() 4 times per change event?

Leave a Reply

Your email address will not be published. Required fields are marked *

Carl de Souza
KEEP LEARNING. KEEP BUILDING.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.