Client Script Types: onLoad, onChange, onSubmit — When to Use Each

There are four Client Script types in ServiceNow. Each fires at a different point in the form lifecycle. Knowing exactly when each fires stops you from writing scripts that silently do nothing — which is the most common Client Script mistake.

onLoad

Fires once when the form loads. Use it to set initial field values, show/hide fields based on loaded data, or call GlideAjax to fetch data you need on page load.

function onLoad() {
    // Hide the resolution field when form first loads if not resolved
    if (g_form.getValue('state') != '6') {
        g_form.setVisible('resolution_notes', false);
    }
}

Do not put logic here that should run on field changes — it will not re-run when a field changes.

onChange

Fires when a specific field value changes. You specify which field triggers it in the Script record. The function receives the new value.

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue === '') return;
    // Only runs when the field actually changes, not on load
    if (newValue == '6') {
        g_form.setMandatory('resolution_notes', true);
        g_form.setVisible('resolution_notes', true);
    } else {
        g_form.setMandatory('resolution_notes', false);
        g_form.setVisible('resolution_notes', false);
    }
}

Critical: Always check isLoading and return early if true. onChange fires once on load with isLoading = true — without this check your script runs twice on page load.

onSubmit

Fires when the user submits the form (Save button). Return false to cancel the submission:

function onSubmit() {
    if (g_form.getValue('state') == '6' && g_form.getValue('resolution_notes') == '') {
        alert('Resolution notes are required when resolving an incident.');
        return false; // Cancels the save
    }
}

onCellEdit

Fires when a cell is edited in a list view — not on forms. Less commonly used but useful for list-based editing validation.

g_form methods you actually use

  • g_form.getValue('field_name') — get display value
  • g_form.setValue('field_name', value) — set value
  • g_form.setMandatory('field_name', true/false) — make mandatory
  • g_form.setVisible('field_name', true/false) — show/hide field
  • g_form.setReadOnly('field_name', true/false) — make read-only
  • g_form.showFieldMsg('field_name', 'message', 'error') — show inline message

Want the complete reference?

This article is part of the NowSpectrum knowledge library. Browse all products for cheat sheets, interview prep, and deep-dive reference guides.

Browse All Products →