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

vkachineni
Kilo Sage
Kilo Sage

Please post your script.

Please mark Correct and click the Thumb up if my answer helps you resolve your issue. Thanks!
Vinod Kumar Kachineni
Community Rising Star 2022

Hi,

I have made changes to my code and it seems to run fine for the scenarios I have tested. You can have a look and probably suggest if any further changes to it might help and whether I am missing any edge case where it might run into recursion again. Below is my code :

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }
    if (oldValue != newValue) {
        var con = confirm("WARNING!! This will change the mapping. ");
		
        if (!con) {
            g_form.setValue('cmdb_ci', oldValue);
            return;
        } else {
            return;
        }
    }
}

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
if (newValue === oldValue)
{
//There is no change. just return
g_form.setValue('cmdb_ci', oldValue);
return;

}
if (newValue != oldValue) {
var con = confirm("WARNING!! This will change the mapping. ");

if (con) {
g_form.setValue('cmdb_ci', newValue);
return;
} else {
g_form.setValue('cmdb_ci', oldValue);
return;
}
}
}

Please mark Correct and click the Thumb up if my answer helps you resolve your issue. Thanks!
Vinod Kumar Kachineni
Community Rising Star 2022

Hey,

I used this script, but it is still going into recursion on Cancel. Do retest and let me know, what could possibly be wrong in this.

 

Thanks.