Prevent an onChange Client Script from going into recursion

Karan Khanna1
ServiceNow Employee
ServiceNow Employee

I have an onChange client script called when a user selects an item for a field using the lookup functionality (here, referring to available CIs and user selects one of the CI from the lookup). If the user has selected a new CI item, then my client script is invoked which warns a user via a prompt on UI to confirm if he wants to go-ahead with the selected item or not? In this case if user confirms, then the new value is set in that field (new CI), else the field is set with the old value (old CI) itself.

In the above scenario, my script is going into recursion, as every item selection triggers an "onChange" event and eventually calling the client script. Would be of great help if someone can suggest a way of handling this or if there is any alternative solution here in terms of the best practices? 

12 REPLIES 12

Hitoshi Ozawa
Giga Sage
Giga Sage

Hi Karan,

As Rand889 mentioned, comparing with "oldValue" won't solve the problem because "oldValue" contains the value when the form is loaded. That is, if the value is entered and then changed, oldValue still will be the value when the form was loaded.

https://community.servicenow.com/community?id=community_blog&sys_id=608428241bd5e810ed6c9979b04bcbd2

The solution is to compare "newValue" with the old CI value.

 

Jan58
Tera Contributor

My issue of endless recursion was caused when I did resetting the value of the field the script is listening to.

 

I fixed it with

return false;

bsiva4567
Tera Contributor

Create a hidden check box variable and use it as a flag. Before using setValue just set this variable as true and in the beginning of of script as something like this
if (isLoading || newValue === '' || g_form.getValue('flag_variable'=="true) {
return;
}