OnChange Client script - check field and set value

Jan5
Tera Contributor

Hello, 

I need any advice with client script since I'm new to ServiceNow.

On Change form, I need a OnChange client script that will check a field two fields State,Risk -  if the State will be set to "Assess"(-6) and field Risk is empty users will receive a warning message that will tell them to fill out Risk before changing to Assess and put field state back to New (-5).

 

Thanks in advice.

Jan 

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

you can use below sample client script

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

if(oldValue != newValue){

if(newValue == -6 && g_form.getValue('risk') == ''){
g_form.addErrorMessage('Please fill risk before changing to Assess');
g_form.setValue('state', -5);

}

}

}

Regards
Ankud

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

View solution in original post

2 REPLIES 2

Mark Roethof
Tera Patron
Tera Patron

Hi there,

The conditions mentioned, you could already achieve through UI Policy and using the condition builder. Then you only need to use script for the warning message and setting the value back.

Have you considered this approach?

For a warning message, have a look at:

g_form.addInfoMessage('your message');
g_form.addErrorMessage('your_message');
g_form.addWarningMessage('your_message');

Ideally, you would also apply getMessage in combination with the Message field. This for higher maintainability of the messages and possible internationalization. Hardcoding the messages is bad practice.

If my answer helped you in any way, please then mark it as helpful.

Kind regards,
Mark
2020 ServiceNow Community MVP
2020 ServiceNow Developer MVP

---

LinkedIn
Community article list

 

 

Kind regards,

 

Mark Roethof

Independent ServiceNow Consultant

10x ServiceNow MVP

---

 

~444 Articles, Blogs, Videos, Podcasts, Share projects - Experiences from the field

LinkedIn

Ankur Bawiskar
Tera Patron
Tera Patron

Hi,

you can use below sample client script

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }

if(oldValue != newValue){

if(newValue == -6 && g_form.getValue('risk') == ''){
g_form.addErrorMessage('Please fill risk before changing to Assess');
g_form.setValue('state', -5);

}

}

}

Regards
Ankud

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