Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

GTSNOW
Giga Guru
In this Article, you will learn how can you set a value on a field of a form on different conditions and scenarios.

Setting the field value on load of the form

Scenario: When incident form is loaded then the value of Caller field should populated with logged in user.
 
Solution : This type of requirement can be achieved with Client Script as it needs to be set when form is loaded in the browser.
 
Script Type : Client Script
 
Name : Populate Caller on the Incident
Table : Incident
UI Type : All
Type : OnLoad
Active : True
Global: True
Script
function onLoad() {
    //Type appropriate comment here, and begin script below

    if (g_form.isNewRecord()) {

        var currentUser = g_user.userID;

        g_form.setValue('caller_id', currentUser);
    }
}

Setting the field value on change of a field

Scenario: When incident form is loaded then the Assignment Group should be populated with Network group.
 
Solution : This type of requirement can be achieved with Client Script as it needs to be set when value of Category field changes to Hardware.
 
Script Type : Client Script
 
Name : Populate Caller on the Incident
Table : Incident
UI Type : All
Type : OnChange
Field: Category
Active : True
Global: True
Script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    //Type appropriate comment here, and begin script below
    if (newValue == 'hardware') {
        //Setting SYSID OF Network Group
        g_form.setValue('assignment_group', '287ebd7da9fe198100f92cc8d1d2154e','Network'); 
    }

}
Comments
Mark Roethof
Tera Patron
Tera Patron

Hi there,

Can you update the g_form.setValue('assignment_group', '287ebd7da9fe198100f92cc8d1d2154e');  part?

This now causes an additional query to be made (= waste of performance). Assignment Group is a reference field, so you should provide the value and the displayValue.

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

---

LinkedIn
Community article list

 

GTSNOW
Giga Guru

Thanks for correcting it.

DrewW
Mega Sage

You can also just set the default value for the field to 

javascript:gs.getUserID();

 

jennv
Mega Guru

hey, i am trying on change, but it doesnt work for me.

Version history
Last update:
‎09-23-2020 12:03 PM
Updated by: