Retain Old value of a field using Onchange client script

Community Alums
Not applicable

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.

Onchange Issue.PNG

Thanks in Advance

Thanks,

Sunil Raikwar

9 REPLIES 9

ghsrikanth
Tera Guru

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


Community Alums
Not applicable

Thanks Srikanth for the response


But unfortunately the solution isn't working.



Getting below error :


Onchange Issue1.PNG



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


Hi Sunil,



gs is not supported at client side. It only works at server side.


Pradeep Sharma
ServiceNow Employee
ServiceNow Employee

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);


  }


  }


}