onChange

The onChange client script runs when a selected field is changed on the form. It is important to note that an onChange script will also run when the form is loaded. This type of script is often used to auto-populate other fields on a form, based on data in the field the onChange script is running on. For example, if a user is selected on a form, other user data on the form, like company and job title, could be populated using an onChange script.

In the same way that ServiceNow provides a script function in onLoad scripts, an onChange function is also provided. This is slightly more complicated, so let's take a look:

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}

//Type appropriate comment here, and begin script below

}

The onChange function gives us five parameters that we can use inside the function in our script. Here is what each of these parameters gives us:

  • control: The dynamic HTML of the field that has changed
  • oldValue: The value in the changed field when the form was loaded
  • newValue: The new value that has been entered into the changed field
  • isLoading: Is true if the form is loading; otherwise, false
  • isTemplate: Is true if the change has occurred as part of a template load; otherwise, false

You can also see that a little scripting has already been done by ServiceNow. This if statement checks if the form is loading or if the new value of the changed field is empty. If either of these cases is true, the script returns from the function, essentially canceling the script. In most cases, this is quite helpful, but it is good to understand this if statement, as sometimes you will want to amend it if you want code to run during loading or on the field changing to an empty value.

For example, if you have cleared a user field where additional user data has been added to the form, you will also want to clear the additional user data. In this instance, you will want to remove the condition where the code returns from the function if the newValue parameter is blank.

When selecting the onChange type, the option to pick a field for the script to run against will be visible to the developer. The fields available in this field are dependent on the value in the table field.

We can see an onChange type client script in Figure 3.2:

Figure 3.2: Sample onChange client script

In the preceding figure, we can see an onChange client script for the problem table. Pay particular attention to the Field name field, which defaults to Active, as that is the field that needs to change for this script to run. It can be easy to forget to change this field and wonder why your script is not executing when you are expecting it to.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.144.32