Retain Old value of a field using Onchange client script
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-14-2016 11:32 AM
Hi,
There are 2 fields on the form :
test : choice field (yes/no)
test1 : reference field
Case 1 : If no is selected from test, test1 should clear the value if it has any.
Case 2 : If yes is selected in test, then test1 should be mandatory.
Case 3 : In test, if first 'yes' is selected, then no and then again changed to yes, then it should return the old value that it contained in test1.
I want to implement this by using an Onchange client script.
Can someone please assist.
Thanks in Advance
Thanks,
Sunil Raikwar
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-14-2016 11:43 AM
Please try this script - onChange on test
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue == '') {
return;
}
var oldTest1 = '';
//Type appropriate comment here, and begin script below
if(newValue == 'no'){
var oldTest1 = g_form.getValue('test1');
g_form.setValue('test1','');
}
else if(newValue == 'yes'){
if(!gs.nil(oldTest1))
g_form.setValue('test1',oldTest1);
g_form.setMandatory('test1');
}
}
Mark if it is helpful or correct, feedback is appreciated
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-14-2016 12:14 PM
Thanks Srikanth for the response
But unfortunately the solution isn't working.
Getting below error :
Below is the thing happening :
When I select no, it does clear value but makes field test 1 mandatory, which should not be the case.
And when I select yes, it gives me the above error.
Thanks,
Sunil Raikwar

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-14-2016 12:15 PM
Hi Sunil,
gs is not supported at client side. It only works at server side.

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
‎03-14-2016 12:14 PM
Hi Sunil,
Here is the client script you have to run. However to retrieve the old value of "u_test1" you have to fetch the scratchpad data from client script. Please refer section 7 here for more info on how to use scratchpad.
Scripting in Business Rules - ServiceNow Wiki
Script :
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue == '') {
return;
}
var oldTest1 = '';
//Type appropriate comment here, and begin script below
if(newValue == 'no'){
g_form.setValue('u_test1','');
}
else if(newValue == 'yes'){
if(oldTest1 = '')
{
g_form.setMandatory('u_test1', true);
}
else
{
g_form.setValue('u_test1', 'SCRATCHPAD'); //set the value here based on scratchpad variable
g_form.setMandatory('u_test1', true);
}
}
}