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:


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?