Client Script in servicenow

Client scripts allow the system to run JavaScript on the client/form (web browser) when client-based events occur, such as when a form loads, after form submission, or when a field changes value.

We can perform below activities using client script.

        1. We can hide and show fields.
        2. We can make fields read only or writable.
        3. Set the value in the fields.
        4. Get the field value.
        5. Modify the options of a choice of dropdown fields.
        6. Display messages based on a value in a field.
        7. Alert message.
        8. Call server side script.
        9. Form validation

Note: Client scripts are not supported on ServiceNow mobile applications.

 

Create New Client Script

In order to create new client script follow below steps:

        1. Navigate to System Definition > Client Scripts
        2. You will be presented with list of all client script. Click on New button.
        3. Fill all the required details and click submit.

Types of Client Script

There are 4 types of client script

        1. onLoad
        2. onChange
        3. onSubmit
        4. onCellEdit

You need to understand each attribute functionality so now let me explain each and every attribute’s functionality in details. 

Field Name Detailed Description
Name Name of Client Script. Use a standard naming scheme to identify custom scripts.
Table Select the table name on which you want to apply the client script.
UI Type Select whether the script executes for Desktop and Tablet or Mobile/Service Portal or All.
Type Select when the script runs: onChange, onLoad, onCellEdit() or onSubmit.

onLoad() — This type of client script runs when the system first renders/load the form and before users can enter data.

onSubmit() — This type of client script runs when a form is submitted.  It is used to validate things on the form and ensure that the submission makes sense. An onSubmit() client script can cancel form submission by returning a value of false.

onChange() — This type of client script runs when a particular field value changes on the form.

onCellEdit() — This type of client script runs when the list editor changes a cell value. Script runs when a particular field value on a list changes. Applies to all records selected.

Note: onCellEdit() client scripts do not apply to dashboard list widgets.

Application Application where this client script resides.
Active Controls whether the script is enabled. Inactive scripts do not execute.
Inherited If selected, this script applies to the specified table and all tables that inherit from it. For example, a client script on the Task table will also apply to the Change, Incident, Problem and all other tables which extend Task.
Global If Global is selected the script applies to all Views. If the Global field is not selected you must specify the View.
View Specifies the View to which the script applies. The View field is visible when Global is not selected. A script can only act on fields that are part of the selected form View. If the View field is blank the script applies to the Default view.
Description This field used to describing the functionality and purpose of the client script.
Messages Use this field to enter message strings that the client script can use as a key to look up a localized message alternative from the message [sys_ui_message] table. Add each message key on a separate line.

For example, if you add the string “My First Message” field to the Messages field, then the instance will look for a localized string from the Message [sys_ui_message] table any time the client script calls:

getMessage(“My First Message”);

Script Contains the client script code.

 

Let’s see each type of client script in details with real world scenarios.
1. onLoad2. onChange3. onSubmit4. onCellEdit

This client script will execute once forms are loaded.

onload client script in servicenow - servicenowhelpdesk.com
Img. Source: ServiceNow

I have explained the above pic in details in the video. Request you to watch it for better understanding.

Now lets take a look on real word example

Real World Scenario

Requirement: Hide “Closed” Incident state and State from everyone accept user who has itil_admin role.

Solution: create onload client script and write below code.

function onload() {
    if (g_user.hasrole('itil_admin'))
        return;

    if (g_form.getvalue('incident_state') != '7')
        g_form.removeoption('incident_state', 7);
    if (g_form.getvalue('state') != '7')
        g_form.removeoption('state', 7);
}

 

 

onChange client script will runs when a particular field value changes on the form.

onchange client script in servicenow - servicenowhelpdesk.com
Img. Source: ServiceNow

I have explained the above pic in details in the video. Request you to watch it for better understanding.

In onChange() client script we will get below OOB parameters/Objects. Let me explain you each object in details.

A. control: the DHTML (Dynamic Hyper Text Markup Language) widget whose value changed.

      • Control parameters are generally used for If we wants to change the dynamically field size, length etc. in ui page. So we will use control parameter inside client script in onChange type. 
      • It’s basically the field for which this client script is written. And it will give you HTML objectfor that field so that you can change or use it as per your need for example restricting field length.
      • Name of the object (field_name) whose value just changed. The object is identified in the Field name field on the Client Script form.
      • To change the field value color we can use this script: style.color = ‘blue’;

 Note: control is not accessible in mobile and service portal. 

 

B. oldVaIue— Value of the control field when the form loaded and prior to the change. For example, if the value of Assigned to changes from Runjay to Suman, the value of the parameter oldValue is Runjay. oldVaIue will always be Runjay (the value when the form loaded) no matter how many times the Assigned to value changes after the original form load.

C. newVaIue— Value of the control field after the change. For example, if the value of Assigned to changes from Runjay to Suman, the value of the parameter newValue will be Suman.

D. isLoading— Boolean value indicating whether the change is occurring as part of a form load. Value is true if change is due to a form load. A form load means all of a form’s fields changed.

E. isTemplate— Boolean value indicating whether the change occurred due to population of the field by a template. Value is true if change is due to population from a template.

Now lets take a look on real word example

Real World Scenario

Requirement: Make Assignment group and assigned to field mandatory if state changes from New to In-Progress.

Solution: create onChange client script and write below code.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
   if (isLoading || newValue === '') {
      return;
   }
    if(newValue == 2){
        g_form.setMandatory('assignment_group', true);
        g_form.setMandatory('assigned_to', true);
    }else{
        g_form.setMandatory('assignment_group', false);
        g_form.setMandatory('assigned_to', false);
    }
   
}	

 

This type of client script runs when a form is submitted.  It is used to validate things on the form and ensure that the submission makes sense. An onSubmit() client script can cancel form submission by returning a value of false.

    • Script runs when a form is saved, updated, or submitted
    • Typically used for field validation
onsubmit client script in servicenow - servicenowhelpdesk.com
Img. Source: ServiceNow

I have explained the above pic in details in the video. Request you to watch it for better understanding.

Now lets take a look on real word example

Real World Scenario

Requirement: If IT fulfiller clicks on Cancel button then make Cancel Reason field mandatory with alert / error stating cancel reason field is mandatory.

Solution: create onSubmit client script and write below code.

function onSubmit() {
   if(g_form.getValue('state') ==8 && g_form.getValue('u_cancel_reason') ==''){
       
       g_form.addErrorMessage('Reason field is mandatory !!');
       return false;
   }
}

 

 

 

This type of client script runs when the list editor changes a cell value. Script runs when a particular field value on a list changes. Applies to all records selected.

In onCellEdit() client script we will get OOB parameters/Objects. Let me explain you each object in details.

Request you to watch it for better understanding.

A. sysIDs: It consist an array of the sys_ids for all items being edited.

B. table: The table of the items being edited.

C. oldValues: The old values of the cells being edited.

D. newValue: The new value for the cells being edited.

E. callback: A callback that continues the execution of any other related cell edit scripts.

If true is passed as a parameter, the other scripts are executed or the change is committed if there are no more scripts. If false is passed as a parameter, any further scripts are not executed and the change is not committed.

 Note: onCellEdit() scripts do not apply to List Widgets on homepages or dashboards. 

Now lets take a look on real word example

Real World Scenario

Requirement: Prevent state being edited from list view of incident if state marked as Resolved or Closed.

Solution: create onCellEdit client script and write below code.

function onCellEdit(sysIDs, table, oldValues, newValue, callback){
var saveAndClose = true;

if(newValue == 6) { //Resolved
alert("You cannot change the State to 'Resolved' from a list");
saveAndClose = false;
}
if(newValue == 7) { //Closed
alert("You cannot change the State to 'Closed' from a list");
saveAndClose = false;
}
callback(saveAndClose);
}

 

 

Join Us

Thanks for reading this article, i hope you liked it, if that so, do like and subscribe my YouTube channel. You can also join our telegram channel to clear your technical doubt.

 

 

 

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here