Making OnChange Work OnLoad: Triggering JavaScript on Page Load






Making OnChange Work OnLoad: A Deep Dive into UI Policy Behavior


Making OnChange Work OnLoad: A Deep Dive into UI Policy Behavior

In the realm of user interface development, particularly within platforms like ServiceNow, UI Policies are indispensable tools for dynamically controlling form behavior. They allow us to show, hide, make mandatory, or set default values for fields based on certain conditions. A common point of confusion, however, revolves around how these policies behave when a form first loads versus when a field’s value changes. This article will demystify the concept of “On Load” behavior in UI Policies and illustrate how to effectively achieve “OnChange”-like functionality right from the moment a form is accessed.

Understanding UI Policies and Their Core Triggers

Before we dive into the specifics, let’s quickly recap what UI Policies are and how they operate. A UI Policy is essentially a server-side script that executes client-side logic to modify the user interface of a form. Unlike client scripts, UI Policies offer a more declarative approach, allowing administrators to define conditions and actions without writing extensive code, although scripting can be incorporated for more complex scenarios.

The primary triggers for UI Policies are:

  • On Load: When the form is initially loaded.
  • On Change: When a specific field’s value is changed by the user.

The critical distinction here lies in the “On Load” checkbox. The reference provided states:

“When the “On Load” checkbox is selected, the conditions and actions specified in the UI Policy are evaluated and applied immediately when the form is loaded. If the “On Load” checkbox is not selected, the UI Policy actions will not be applied when the form is initially loaded. Instead, the actions will only be triggered when a specific field or condition is met on the form.”

This is a fundamental concept. If “On Load” is unchecked, the UI Policy sits dormant until a user interacts with the form in a way that satisfies its conditions. This is where the desire to have “OnChange” logic execute on load emerges.

The “OnChange” Illusion: Why It Doesn’t Directly Apply on Load

The term “OnChange” in UI Policies explicitly means “when a field’s value changes.” When a form loads, no field has “changed” in the user’s interaction sense. The values are populated from the database. Therefore, a UI Policy configured *only* for “OnChange” will not run its actions the moment the form appears. It waits for a user to type, select, or otherwise alter a field’s value.

Consider a common scenario: You have a “Type” field. Based on the selected “Type,” you want to show or hide a “Speciality” field. If you create a UI Policy with the condition “Type is ‘X'” and the action is “Show Specialty Field,” and you *don’t* check “On Load,” then when the form loads with “Type” already set to ‘X’, the “Speciality” field will remain hidden until the user *changes* the “Type” field to something else and then back to ‘X’, or perhaps changes another field that triggers the policy.

This is where the need to bridge the gap between initial form state and desired dynamic behavior becomes apparent. We want the form to *look* as if the “OnChange” logic has already run, reflecting the pre-populated field values.

Achieving “OnChange” Behavior on Load: The “On Load” Checkbox is Your Best Friend

The most direct and intended way to make your “OnChange” logic execute when the form loads is to simply **select the “On Load” checkbox on your UI Policy**. This might sound too simple, but it’s the core mechanism provided by the platform. When “On Load” is checked, the UI Policy evaluates its conditions based on the *current* state of the form, which includes any pre-populated values.

How it Works in Practice

Let’s revisit our “Type” and “Specialty” field example.
If you have a UI Policy with the following configuration:

  • Short description: Control Specialty Field Visibility
  • Table: Incident (or your relevant table)
  • Conditions:
    • Type is Electronic
  • UI Policy Actions:
    • Field: Specialty
    • Visible: True
    • Mandatory: True (optional, depending on your needs)
  • “On Load” checkbox: Checked
  • “Reverse if false”: Checked (highly recommended for dynamic visibility)

Now, when a new Incident record is opened, and the “Type” field is *not* selected (i.e., it’s empty), the condition “Type is Electronic” is false. The UI Policy will execute, and because “Reverse if false” is checked, it will make the “Specialty” field invisible and not mandatory.

However, if you open an existing Incident record where the “Type” field was saved as “Electronic,” the UI Policy will run on load. The condition “Type is Electronic” will be true. The UI Policy will then execute its actions, making the “Specialty” field visible and mandatory.

This demonstrates that by checking “On Load,” the UI Policy effectively simulates an “OnChange” event for the fields that determine its conditions, using the values present at load time.


Real-World Example: Incident Prioritization

Imagine you’re working on an Incident Management system. You want the “Impact” and “Urgency” fields to dictate the “Priority” field. Typically, you’d have a matrix or rule:

  • Impact High, Urgency High = Priority 1 (Critical)
  • Impact High, Urgency Medium = Priority 2 (High)
  • …and so on.

You could implement this with a UI Policy:

  • Short description: Set Incident Priority
  • Table: Incident
  • Conditions:
    • Impact is High AND Urgency is High
  • UI Policy Actions:
    • Field: Priority
    • Value: 1 – Critical
  • “On Load” checkbox: Checked
  • “Reverse if false”: Checked (important to reset if conditions change)

Additionally, you’d create *separate* UI Policies for each combination of Impact and Urgency that results in a different Priority. For instance, another UI Policy for “Impact is High AND Urgency is Medium” setting Priority to “2 – High”.

By checking “On Load” for all these UI Policies, when an Incident is created or opened, the system will immediately evaluate the “Impact” and “Urgency” values and set the “Priority” accordingly, even before the user touches any fields. If an existing Incident was saved with Impact “High” and Urgency “High,” it will load with Priority “Critical.” If a new Incident is created with no Impact or Urgency selected, the “Reverse if false” actions on these policies would ensure the Priority field isn’t set incorrectly.

When “On Load” Alone Isn’t Enough: The Role of Client Scripts

While checking “On Load” is the primary method, there are scenarios where UI Policies, even with “On Load” checked, might have limitations, especially if the logic is highly interdependent or involves complex calculations not easily expressed in UI Policy conditions.

This is where Client Scripts come into play. A client script can be written to execute code directly on the client-side. An “OnLoad” client script is the direct counterpart to the “On Load” checkbox for UI Policies.

Using Client Scripts for “OnChange” on Load

If you have a UI Policy that relies on values from multiple fields, or if the logic to determine a field’s visibility/value is complex, you might consider a client script. The principle remains the same: the client script runs when the form loads.

Consider a scenario where the visibility of field ‘C’ depends on the *combination* of field ‘A’ and field ‘B’ in a way that’s hard to define with simple AND/OR logic in UI Policy conditions. Or perhaps, field ‘A’ is populated by a glide record lookup based on another field, and you want field ‘C’ to react to that lookup’s result immediately.

In such cases, you would write an “OnLoad” Client Script.


function onLoad() {
    // Get values from fields A and B
    var valueA = g_form.getValue('field_a');
    var valueB = g_form.getValue('field_b');

    // Implement your complex logic here
    if (valueA === 'SomeValue' && valueB === 'AnotherValue') {
        // Make field C visible and mandatory
        g_form.setVisible('field_c', true);
        g_form.setMandatory('field_c', true);
    } else {
        // Make field C invisible or not mandatory
        g_form.setVisible('field_c', false);
        g_form.setMandatory('field_c', false);
    }
    // You can also set values, clear fields, etc.
}
    

This “OnLoad” client script executes when the form loads, reading the initial values of ‘field_a’ and ‘field_b’ and then applying its logic to ‘field_c’. This effectively achieves the “OnChange” behavior (reacting to field values) but on form load.


Advanced Example: Dependent Field Logic with Client Script

Let’s say you have a “Product Category” field, and based on its selection, you want to dynamically populate and show a “Sub-Category” field. The sub-categories might be loaded via a background script or a related table lookup. While UI Policies can handle simple dependencies, complex, multi-level, or dynamically generated options are better suited for client scripts.

You might have an “OnLoad” UI Policy that sets a default value for “Product Category” if it’s a new record and a specific context exists. Then, you’d have an “OnLoad” Client Script:

  • Short description: Dynamically Populate Sub-Category
  • Table: Incident
  • Type: OnLoad

function onLoad() {
    var productCategory = g_form.getValue('product_category');

    // Check if productCategory has a value (it might be set by UI Policy or loaded)
    if (productCategory) {
        // Logic to fetch or determine available sub-categories based on productCategory
        // This could involve a GlideAjax call to a script include for server-side data retrieval
        // For simplicity, let's assume we have predefined options or a way to fetch them.
        var subCategories = getSubCategoriesForCategory(productCategory); // Hypothetical function

        // Clear existing options in sub-category field (if applicable)
        g_form.clearOptions('sub_category');

        // Add new options to the sub-category field
        if (subCategories && subCategories.length > 0) {
            for (var i = 0; i < subCategories.length; i++) {
                g_form.addOption('sub_category', subCategories[i].value, subCategories[i].label);
            }
            // Make sub_category visible and mandatory if there are options
            g_form.setVisible('sub_category', true);
            g_form.setMandatory('sub_category', true);
            // Optionally, set a default sub-category if one exists
            // g_form.setValue('sub_category', defaultSubCategoryValue);
        } else {
            // If no sub-categories, hide and clear the field
            g_form.setVisible('sub_category', false);
            g_form.setMandatory('sub_category', false);
        }
    } else {
        // If product category is not selected, ensure sub-category is hidden
        g_form.setVisible('sub_category', false);
        g_form.setMandatory('sub_category', false);
    }
}

// Hypothetical function to get sub-categories (in a real scenario, this would be server-side)
function getSubCategoriesForCategory(category) {
    // In a real system, this would query a table or use a GlideAjax call
    // Example:
    if (category === 'Hardware') {
        return [{ value: 'laptop', label: 'Laptop' }, { value: 'desktop', label: 'Desktop' }];
    } else if (category === 'Software') {
        return [{ value: 'os', label: 'Operating System' }, { value: 'app', label: 'Application' }];
    }
    return [];
}
        

This client script runs on load, inspects the “Product Category,” fetches relevant “Sub-Category” options, populates the field, and sets its visibility and mandatory status. It’s effectively performing an “OnChange”-like update based on the initial state.

Troubleshooting Common Issues

Even with the “On Load” checkbox, you might run into situations where your intended behavior doesn’t manifest. Here’s how to troubleshoot:

Troubleshooting Checklist:

  • Is “On Load” Checked? This is the most common oversight. Double-check your UI Policy configuration.
  • Are Conditions Being Met?
    • Use the “Watch” tab in the UI Policy form to see if your conditions are evaluating correctly on load.
    • Ensure field names in conditions are spelled correctly.
    • Verify the exact values you are comparing against (case sensitivity, whitespace).
    • If using choices, ensure you are using the value of the choice, not the label.
  • Order of Execution Matters:
    • If you have multiple UI Policies or a UI Policy and a Client Script, their order of execution can impact the final state of the form.
    • UI Policies generally execute in the order of their “Order” field.
    • Client Scripts of type “OnLoad” execute after UI Policies. If your client script needs to *override* or *refine* UI Policy actions, it should be written to do so.
    • Test by temporarily disabling other UI Policies or client scripts to isolate the problem.
  • “Reverse if false” is Crucial: If you want a field to be hidden when a condition is *not* met (which is typical for dynamic visibility), ensure “Reverse if false” is checked on your UI Policy actions. Without it, if the condition becomes false, the previous state of the action is not reverted.
  • Complex Field Types: Be mindful of how UI Policies interact with related lists, choice lists with dynamic variables, or fields populated by other means (e.g., scheduled imports, Business Rules that run *after* insert/update). Sometimes, these processes might complete *after* the initial “On Load” evaluation.
  • Caching Issues: Occasionally, browser caching or platform-level caching can cause unexpected behavior. Try clearing your browser cache or logging out and back in. If it’s a persistent issue, consider checking the system logs for any client-side errors.
  • UI Policy vs. Client Script Conflict: If you’re using both, ensure they aren’t working against each other. A client script might be setting a value that a UI Policy then immediately changes back, or vice-versa.

Interview Relevance

Understanding UI Policy behavior, especially the “On Load” aspect and how it enables “OnChange” effects, is a common topic in technical interviews for roles involving platform development (like ServiceNow administrators, developers, or business analysts). Here’s why:

Key Interview Points:

  • Explaining UI Policy Triggers: Be ready to clearly differentiate between “On Load” and “On Change” triggers for UI Policies.
  • Achieving OnChange on Load: The interviewer might ask, “How would you make a UI Policy’s field visibility logic apply when a form first opens?” Your answer should immediately point to checking the “On Load” checkbox.
  • Client Scripts vs. UI Policies: Discuss when to use each. UI Policies for simpler, declarative rules; Client Scripts for complex logic, server-side calls, or intricate UI manipulations.
  • Troubleshooting Scenarios: Be prepared to walk through a common troubleshooting step for UI Policies, such as checking conditions or the “Reverse if false” property.
  • Impact of Order: An interviewer might probe your understanding of execution order, especially when UI Policies and Client Scripts are involved. Explain how “OnLoad” client scripts run *after* UI Policies.
  • “Reverse if false”: This property is often a differentiator. Explain its purpose and why it’s critical for dynamic form behavior.
  • Real-world Examples: Being able to cite examples like the Incident Prioritization or Dynamic Sub-Category population demonstrates practical application of these concepts.

Being able to articulate these points clearly shows a solid grasp of front-end form customization and a practical understanding of how to build intuitive user interfaces.

Conclusion

The concept of making “OnChange” work on “Load” boils down to understanding that the “On Load” checkbox on a UI Policy is precisely designed to evaluate and apply your defined conditions and actions based on the form’s initial state. By diligently configuring your UI Policies with “On Load” enabled, and leveraging “Reverse if false” where appropriate, you can ensure that forms behave dynamically from the moment they are opened, providing a seamless user experience.

While client scripts offer a more powerful and flexible approach for complex scenarios, the UI Policy’s “On Load” feature is the most straightforward and often sufficient method for achieving this desired behavior. Mastering these fundamental aspects of UI Policy management is key to effectively customizing user interfaces and is a valuable skill for anyone working with platforms that rely on dynamic form logic.


Scroll to Top