Client Script - OnChange with Realtime Scenarios and Use Cases

ServiceNow is a potent IT service management (ITSM) platform that aids businesses in streamlining their IT processes.

The ability of ServiceNow to create the platform for particular business requirements is one of its key characteristics. A crucial component of this customization is client scripts.

which lets programmers run JavaScript code in the user's browser on the client side.

 Client side

An OnChange Client Script
 

What Is It?

In ServiceNow, a client script OnChange is executed whenever the value of a specific field varies.

This is especially helpful for carrying out calculations, enforcing business rules based on user input, and dynamically updating other fields.

OnChange scripts enhance user experience by providing real-time feedback and updates without the need to refresh the page.

Writing a Client Script for OnChange

Take the following actions to create an OnChange client script.

  1. Locate and fill out the relevant form: Navigate to the table (such as Incident, Change Request) where you wish to add the client script.
  2. Launch the Client Script application: Type "Client Scripts" into the left-hand navigation pane, then click the relevant option under the "System Definition" module.
  3. Form a fresh Client Script: To create a new client script, click the "New" button.
  4. Set up the client script as follows: Provide the following information on the form:
  5. Name: A fitting moniker for the play.
  6. Table: The table (such as Incident) that the script will execute on.
  7. Type: From the dropdown menu, choose "onChange".
  8. Field: Indicate which field, when its value changes, will cause the script to run.

Developing a Client Script for OnChange

  1. Tnge Request: where you wish to add the client script.
  2. Launch the Client Script application: Type "Client Scripts" into the left-hand navigation pane, then click the relevant option under the "System Definition" module.
  3. Form a fresh Client Script: To create a new client script, click the "New" button.
  4. Set up the client script as follows: Provide the following information on the form:
  5. Name: A fitting moniker for the play.
  6. Table: The table (such as Incident) that the script will execute on.
  7. Type: From the dropdown menu, choose "onChange".
  8. Field: Indicate which field, when its value changes, will cause the script to run.

Basic Structure of an OnChange Client Script

Here's a basic example of an OnChange client script that runs when the priority field changes on an incident record.

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

    // Your script logic here
    g_form.addInfoMessage('Priority has been changed to ' + newValue);
}

Real-Time Scenarios and Use Cases
 

Auto-populate fields based on selection

Scenario: When a user selects a category, the subcategory field should be automatically populated based on the selected category.

Use Case

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

    // Fetch subcategories based on the selected category
    var ga = new GlideAjax('GetSubCategories');
    ga.addParam('sysparm_name', 'getSubCategories');
    ga.addParam('sysparm_category', newValue);
    ga.getXMLAnswer(function(response) {
        var subcategories = JSON.parse(response);
        g_form.clearOptions('subcategory');
        subcategories.forEach(function(subcategory) {
            g_form.addOption('subcategory', subcategory.value, subcategory.label);
        });
    });
}

Enforcing Mandatory Fields

Scenario: If the incident type is set to "Major Incident," certain fields should become mandatory.

Use Case

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

    if (newValue === 'major') {
        g_form.setMandatory('impact', true);
        g_form.setMandatory('urgency', true);
    } else {
        g_form.setMandatory('impact', false);
        g_form.setMandatory('urgency', false);
    }
}

Conditional Display of Fields

Scenario: Display additional information fields only if the user selects a specific option from a dropdown.

Use Case

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

    if (newValue === 'specific_option') {
        g_form.setDisplay('additional_info', true);
    } else {
        g_form.setDisplay('additional_info', false);
    }
}

Real-Time Calculations

Scenario. Automatically calculate and display the total cost based on the quantity and unit price fields.

Use Case

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

    var quantity = g_form.getValue('quantity');
    var unitPrice = g_form.getValue('unit_price');
    var totalCost = quantity * unitPrice;

    g_form.setValue('total_cost', totalCost);
}

Best practices to follow

  • Maintaining an efficient script and avoiding lengthy operations will help to guarantee a seamless user experience.
  • Cut Down on Server Calls: Reduce the amount of GlideAjax calls to prevent problems with performance.
  • Employ Appropriate Error Handling: Make sure your script gracefully handles errors, particularly when addressing server calls.
  • Test Carefully: Make sure your scripts function as intended and don't introduce any bugs by running them through a variety of scenarios.
  • In summary
  • OnChange client scripts are effective instruments for developing dynamic and adaptable user interfaces.
  • You can improve the user experience by giving real-time updates and feedback by utilizing these scripts.

By following best practices, you can ensure that your scripts are efficient, maintainable, and provide a positive user experience. Hope this was helpful, Bye until next time, and happy reading.


Similar Articles