Client Scripts in ServiceNow- Simplified with Real-Time Use Cases

Hi guys, so in this article, we will be seeing about the client scripts.

In ServiceNow, client scripts are an effective tool for improving the platform's functionality and user experience. They provide dynamic behavior and interactions without requiring server-side processing by enabling developers to run JavaScript code directly within the user's browser.

Client Script new record

Client scripts offer flexibility in handling behavior based on user actions and can be applied to a variety of elements and events within ServiceNow, including forms, fields, and buttons.

The various client script types that ServiceNow offers—onChange, onSubmit, onCellEdit, and onLoad—will be discussed in this article.

We'll go over each type's use case, offer a sample of code that shows how it's implemented, and point out situations in which it works well. let's get started.

1. onChange Script for client

When a field on a form changes, the onChange client script is triggered. It is frequently used for calculations, validation, and dynamic updates that are dependent on user input. assuming if you are changing caller or a state, this is handled by an onchange script.

Use case. Verify user input entered into a form field; if it is incorrect, display an error message.

function onChangeClientScript() {
    var fieldValue = g_form.getValue('field_name');  
    // Performing validation logic
    if (fieldValue < 0) {
        g_form.showFieldMsg('field_name', 'Value must be greater than 0', 'error');
    } else {
        g_form.clearMessages('field_name');
    }
}

Use case example. Suppose you have a form for submitting employee expense reports, and you want to ensure that the amount entered in the "Expense Amount" field is a positive value.

Using an onChange client script, you can validate the input in real-time and provide immediate feedback to the user if the value is invalid.

2. onSubmit Client Script

When a form is submitted—either by clicking the submit button or by performing a similar action like update —the onSubmit client script runs.

It helps complete last-minute validation checks before storing data or starting further processes after a form is submitted. for example, if you want a field to be mandatory while the submit is clicked and if the mandatory field is not filled, you can throw an error using this submit script.

Use case. Before allowing submission, validate several fields on a form, and if validation fails, stop the form from being saved.

function onSubmitClientScript() {
    var fieldValue1 = g_form.getValue('field1');
    var fieldValue2 = g_form.getValue('field2');  
    // Perform validation logic
    if (fieldValue1 === '' || fieldValue2 === '') {
        alert('Please fill in all required fields');
        return false; // Prevent form submission
    } 
    return true; // Allow form submission
}

Use case example. In a service request form, you may have several mandatory fields that must be filled out before the request can be submitted. Using an onSubmit client script, you can validate all required fields and prompt the user to complete any missing information before allowing the form to be submitted.

3. onCellEdit Client Script

The onCellEdit client script triggers when a cell in a list or related list is edited. It is typically used to perform calculations, updates, or validations on list data in real time.

Use case. Calculate the total cost when quantity and unit price fields are edited in a list.

When a cell in a list or related list is edited, the onCellEdit client script is triggered. Real-time calculations, updates, and validations of list data are usually carried out using it.

function onCellEditClientScript() {
    var quantity = g_list.getCellValue(rowSysId, 'quantity');
    var unitPrice = g_list.getCellValue(rowSysId, 'unit_price');   
    // Calculate total cost
    var totalCost = quantity * unitPrice;
    // Update total cost field in the list
    g_list.setValue(rowSysId, 'total_cost', totalCost);
}

Use case. Determine the overall expense when a list's quantity and unit price fields are modified.

Use case example. You might have a list of products with columns for quantity and unit price in an inventory management application. When the quantity or unit price is changed, you can automatically determine the total cost using an onCellEdit client script, giving users instant insight into the financial effects of their changes.

4 . Client Script onLoad

When a page or form loads, or is refreshedthe onLoad client script gets started. It is frequently used to set up form fields, get more data, or alter the user interface in response to certain circumstances.

Use case. When the form loads, populate a dropdown field with a list of options that were retrieved from a reference table.

function onLoadClientScript() {
    // Query reference table to retrieve options
    var options = [];
    var gr = new GlideRecord('reference_table');
    gr.query();
    while (gr.next()) {
        options.push({ value: gr.getValue('value'), label: gr.getValue('label') });
    }   
    // Populate dropdown field with options
    g_form.addOption('dropdown_field', options);
}

Use case example. Let's say you have a form where one of the fields is a drop-down list with the categories that are available for creating new incidents. To guarantee that users have access to the most recent category options when submitting an incident, you can dynamically populate the dropdown with options retrieved from a reference table using an onLoad client script.

Developers can effectively customize and extend ServiceNow applications to meet specific business requirements and user needs by knowing when and how to use each type of client script.

Let me also drop you a few best practices for writing client-side scripts.

Best practices for writing a better client script

Minimize Script complexity

The major point is if it can be achieved using UI policies go with that and try to minimize using the scripting as much as possible.

  • Keep client scripts concise and focused on specific tasks.
  • Avoid nesting multiple levels of logic within a single script.
  • Break down complex tasks into smaller, manageable functions for better readability and maintainability.

Use Glide APIs effectively

  • Utilize ServiceNow's Glide APIs to interact with platform data and functionality.
  • Familiarize yourself with commonly used APIs such as `g_form`, `g_user`, `g_list`, and `g_modal`.
  • Refer to the ServiceNow API documentation for comprehensive guidance on available methods and properties.

Optimize performance

  • Be mindful of performance implications when writing client scripts.
  • Minimize DOM manipulation and avoid unnecessary loops or computations.
  • Consider asynchronous operations for time-consuming tasks to prevent blocking the user interface.

Implement Error Handling

  • Validate user input and anticipate potential error scenarios.
  • Provide meaningful error messages to guide users when issues arise.
  • Handle exceptions gracefully to prevent script execution from halting abruptly.

Document your code

  • Document client scripts thoroughly to facilitate understanding and maintenance.
  • Use descriptive comments to explain the purpose of functions, variables, and complex logic.
  • Document any dependencies, assumptions, or limitations to aid future development efforts.

Follow Naming conventions

  • Adhere to consistent naming conventions for functions, variables, and script files.
  • Use descriptive names that convey the purpose and context of each script element.
  • Follow ServiceNow's recommended naming conventions to promote clarity and consistency.

Version control

  • Utilize version control systems to manage changes to client scripts effectively.
  • Track revisions, document changes, and collaborate with team members using version control tools.
  • Ensure that only authorized users have access to modify client scripts in production environments.

Summary

The client scripts are essential for improving ServiceNow applications' usability and functionality. Developers can expedite data entry and validation procedures, create dynamic and responsive interfaces, and enhance end-user usability by utilizing the onChange, onSubmit, onCellEdit, and onLoad client script types.

If this article helps let me know about it in the comments and if you are interested in any other topic feel free to comment below, happy coding.


Similar Articles