How to change a field value when state changes using Onchange script.

M Krishna Chai1
Giga Contributor

Hi,

I am working on a requirement , wherein when the state value changes, the value in one of the custom created String field(u_string_2) should change. I tried using Onchange Script but it's not working. Also in 'isLoading' function the alert is working, but in the next steps alert is not popping up, I am mentioning the code below.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading )
{

alert(newValue);
return;
}


if(newValue == '2'){
  g_form.setValue('u_string_2', 'ABC');
  alert(newValue);
}
else if(newValue == 3){
  g_form.setValue('u_string_2','LMN');
  alert(newValue);

}

}

Ankur Bawiskar
Tera Patron

Hi,

Is the state value integer? if yes then no need of quotes while comparing

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading)
{

alert(newValue);
return;
}


if(newValue == 2){
  g_form.setValue('u_string_2', 'ABC');
  alert(newValue);
}
else if(newValue == 3){
  g_form.setValue('u_string_2','LMN');
  alert(newValue);

}

}

Mark Correct if this solves your issue and also mark 👍 Helpful if you find my response worthy based on the impact.
Thanks
Ankur

Regards,
Ankur
Certified Technical Architect  ||  10x ServiceNow MVP  ||  ServiceNow Community Leader

Hi Ankur,

I believe it should work with quotes also. 

 

Thanks,

Mohit Kaushik

Thanks,
Mohit Kaushik
ServiceNow MVP (2023-2025)

Yes it works with quotes as well.

Regards

Regards,
Ankur
Certified Technical Architect  ||  10x ServiceNow MVP  ||  ServiceNow Community Leader

Mohit Kaushik
Mega Sage

Hey Krishna,

It should work as per your script.

 

when the form got loaded, after that did you try to to change the state field?

How are you changing the state field, after opening the form or you are trying your script to work once the form is loaded and field is already changed.

I mean to say, onChange client script works when you do some modification in the form for the value which you are using in your script.

It will be good if you can post some screenshots while playing with your script.

 

Please mark this answer correct if it resolved the query and mark it helpful too if it helped you at all.

Thanks,

Mohit Kaushik

Thanks,
Mohit Kaushik
ServiceNow MVP (2023-2025)