Adding a JavaScript Function to a Field in Dynamics 365 Power Apps On Load with addOnChange

2 Comments

In this post we will look at how to add a function to field in Dynamics 365 / Power Apps, so when a form loads, the function will run on change of the field. We can do this by using addOnChange.

Let’s say I have a field called My Optional Field (new_myoptionalfield) which is on an entity called My New Entity. The field is on the main form:

Now let’s say when this form loads, we want to bind a JavaScript function to this field. The function will simply display an alert to the user, “Field has changed”.

On the form, let’s create a new script on load of the form. We will use the context to get the field, new_myoptionalfield, then use addOnChange to bind our function, DisplayAlert, to the field. Note the execution context is passed automatically as the first parameter to the function in case we need it:

function OnLoad(executionContext) {
   var formContext = executionContext.getFormContext();
   formContext.getAttribute("new_myoptionalfield").addOnChange(DisplayAlert)
}

function DisplayAlert(executionContext) {
     alert("Field has changed");
}

Add this to the form OnLoad:

Passing the Context:

Publish the customization.

Now, go to the form, and add a value to the field My Optional Field. We see our alert displayed. If we tab in and out of the field, this will not run, only on field changing:

 

THANKS FOR READING. BEFORE YOU LEAVE, I NEED YOUR HELP.
 

I AM SPENDING MORE TIME THESE DAYS CREATING YOUTUBE VIDEOS TO HELP PEOPLE LEARN THE MICROSOFT POWER PLATFORM.

IF YOU WOULD LIKE TO SEE HOW I BUILD APPS, OR FIND SOMETHING USEFUL READING MY BLOG, I WOULD REALLY APPRECIATE YOU SUBSCRIBING TO MY YOUTUBE CHANNEL.

THANK YOU, AND LET'S KEEP LEARNING TOGETHER.

CARL

https://www.youtube.com/carldesouza

 

ABOUT CARL DE SOUZA

Carl de Souza is a developer and architect focusing on Microsoft Dynamics 365, Power BI, Azure, and AI.

carldesouza.comLinkedIn Twitter | YouTube

 

2 Responses to Adding a JavaScript Function to a Field in Dynamics 365 Power Apps On Load with addOnChange

  1. I am using a decimal number type filed. If I add text value to the field, the validation triggers before the onChange event. Does the default validation fire before the onChange event? If so, how do I handle it? Thank you.

Leave a Reply

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