Prevent an onChange Client Script from going into recursion
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-29-2019 06:36 AM
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?
- Labels:
-
Best Practices
-
Scripting and Coding

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
05-18-2022 06:40 PM
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.
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
11-13-2023 04:59 AM
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;
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
07-15-2025 12:19 AM
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;
}