Client Scripts
Client Scripts in ServiceNow are JavaScript code segments that run on the client side (in the user's web browser) when forms are loaded, modified, or submitted. They are a fundamental component of the Application User Interface and play a critical role in enhancing the user experience by providing … Client Scripts in ServiceNow are JavaScript code segments that run on the client side (in the user's web browser) when forms are loaded, modified, or submitted. They are a fundamental component of the Application User Interface and play a critical role in enhancing the user experience by providing real-time interactivity without requiring server round-trips. There are four main types of Client Scripts: 1. **onLoad**: Executes when a form is first loaded in the browser. It is commonly used to set default field values, hide or show fields, or display informational messages to the user upon opening a record. 2. **onChange**: Triggers when a specific field value changes on the form. This is useful for dynamically updating related fields, performing field validations, or modifying the form layout based on user input. 3. **onSubmit**: Runs when the user submits or saves the form. It is typically used to validate data before it is sent to the server. If validation fails, the script can abort the submission and prompt the user to correct errors. 4. **onCellEdit**: Executes when a field value is changed in a list view (list editing). This allows developers to apply logic when users edit records directly from a list rather than opening the full form. Client Scripts have access to the GlideForm (g_form) API, which provides methods to manipulate form fields, such as setting values, making fields mandatory, showing or hiding fields, and displaying messages. They can also use the GlideUser (g_user) API to access information about the currently logged-in user. Best practices for Client Scripts include minimizing server calls using GlideAjax for asynchronous operations, keeping scripts lightweight to avoid performance degradation, and using UI Policies for simple show/hide or mandatory logic instead of writing custom scripts. For ServiceNow Certified Application Developers, understanding Client Scripts is essential for building responsive, user-friendly applications that deliver seamless form interactions and robust client-side validation.
Client Scripts in ServiceNow – Complete Guide for CAD Exam
Client Scripts in ServiceNow
Why Are Client Scripts Important?
Client Scripts are one of the most fundamental client-side scripting mechanisms in ServiceNow. They allow developers to control the behavior and appearance of forms in real-time as users interact with them. Understanding Client Scripts is critical for the ServiceNow Certified Application Developer (CAD) exam because they are heavily tested and represent a core competency for any ServiceNow developer. Without Client Scripts, forms would be static and unable to respond dynamically to user input, resulting in poor user experience and inefficient data entry processes.
What Are Client Scripts?
Client Scripts are JavaScript code that runs on the client side (in the user's web browser) when a form loads, changes, or is submitted. They are used to manage form field behaviors such as making fields mandatory, setting field values, showing or hiding fields, and displaying alert messages.
There are four types of Client Scripts:
1. onLoad
Runs when a form is first loaded in the browser. Use this to set default values, hide or show fields, or make fields read-only when the form initially renders.
Example: Setting a field to read-only when the form loads based on a condition.
2. onChange
Runs when a specific field value changes on the form. This script requires you to specify which field to monitor. The function receives the following parameters: control, oldValue, newValue, isLoading, and isTemplate.
Example: When the Priority field changes to 1 - Critical, automatically set the Assignment Group to a specific team.
3. onSubmit
Runs when the form is submitted (when the user clicks Save, Update, or Submit). This is commonly used for form validation. If the function returns false, the submission is cancelled.
Example: Preventing form submission if a required custom validation fails, such as ensuring a description has more than 20 characters.
4. onCellEdit
Runs when a user updates a field value directly from a list (using list editing). This is similar to onChange but applies to list view edits rather than form view edits.
Example: Validating a field change made inline in a list view.
How Do Client Scripts Work?
Client Scripts use the GlideForm (g_form) API to interact with the form. The g_form object provides methods to manipulate form fields. Key methods include:
- g_form.setValue(fieldName, value) – Sets the value of a field
- g_form.getValue(fieldName) – Gets the current value of a field
- g_form.setMandatory(fieldName, true/false) – Makes a field mandatory or not
- g_form.setVisible(fieldName, true/false) – Shows or hides a field
- g_form.setReadOnly(fieldName, true/false) – Makes a field read-only or editable (also known as setDisabled in older versions)
- g_form.addInfoMessage(message) – Displays an informational message at the top of the form
- g_form.addErrorMessage(message) – Displays an error message at the top of the form
- g_form.showFieldMsg(fieldName, message, type) – Displays a message below a specific field
- g_form.clearMessages() – Clears all messages on the form
- g_form.getReference(fieldName, callback) – Retrieves the GlideRecord for a reference field (asynchronous with callback)
- g_form.addOption(fieldName, value, label) – Adds a choice option
- g_form.removeOption(fieldName, value) – Removes a choice option
- g_form.clearOptions(fieldName) – Removes all options from a choice field
Client Scripts also have access to the GlideUser (g_user) object to get information about the currently logged-in user:
- g_user.userName – The username of the logged-in user
- g_user.firstName – The first name
- g_user.lastName – The last name
- g_user.userID – The sys_id of the user
- g_user.hasRole(roleName) – Checks if the user has a specific role
Key Configuration Fields in a Client Script Record:
- Name: A descriptive name for the script
- Table: The table the script applies to
- Type: onLoad, onChange, onSubmit, or onCellEdit
- Field name: (onChange and onCellEdit only) The field to monitor for changes
- Active: Whether the script is active or not
- Inherited: Whether the script runs on extended (child) tables
- Global: Whether the script applies to all application scopes
- UI Type: Desktop, Mobile/Service Portal, or Both
- Script: The actual JavaScript code
Important Best Practices:
1. Minimize server calls from Client Scripts. Client Scripts run in the browser, and making synchronous server calls (like GlideRecord queries) can severely degrade performance. Use GlideAjax for asynchronous server-side calls when needed.
2. Never use GlideRecord in a Client Script. While technically possible, using GlideRecord on the client side makes synchronous AJAX calls, which block the browser and hurt performance. Use GlideAjax with a Script Include (marked as Client Callable) instead.
3. Use g_form.getReference() with a callback function to asynchronously retrieve reference field data, rather than the synchronous version without a callback.
4. Use the isLoading parameter in onChange scripts to prevent the script from executing when the form first loads. The isLoading parameter is true during form load, so you typically add: if (isLoading) return; at the beginning of your onChange script.
5. Use the isTemplate parameter to check if the form is being populated from a template. You can add: if (isTemplate) return; if you don't want the script to fire during template application.
6. Keep Client Scripts lightweight. Heavy processing should be done server-side using Business Rules or Script Includes.
7. Use UI Policies instead of Client Scripts when you only need to set fields as mandatory, visible, or read-only. UI Policies are easier to maintain, require no coding, and are the recommended approach for simple field attribute changes.
Client Scripts vs. UI Policies:
- UI Policies are preferred for simple actions (mandatory, visible, read-only) because they are configuration-based and easier to maintain
- Client Scripts are needed for more complex logic that UI Policies cannot handle (e.g., setting values, adding messages, complex validations, manipulating choice lists)
- When both exist, UI Policies run after Client Scripts, so UI Policy settings may override Client Script settings for field attributes
Client Scripts vs. Business Rules:
- Client Scripts run in the browser; Business Rules run on the server
- Client Scripts provide immediate visual feedback to users; Business Rules process data during database operations
- Client Scripts use the g_form and g_user APIs; Business Rules use the server-side GlideRecord and current/previous objects
- Client Scripts do NOT run when records are modified via web services, import sets, or server-side scripts; Business Rules do
onChange Script Function Signature:
function onChange(control, oldValue, newValue, isLoading, isTemplate) { }
onLoad Script Function Signature:
function onLoad() { }
onSubmit Script Function Signature:
function onSubmit() { }
Return false to prevent the form from being submitted.
Exam Tips: Answering Questions on Client Scripts
1. Know the four types cold. The exam frequently asks which type of Client Script to use in a given scenario. Remember: onLoad (form opens), onChange (field changes), onSubmit (form saves/submits), onCellEdit (list field edit).
2. Remember the onChange parameters. Questions may test your knowledge of the function signature: control, oldValue, newValue, isLoading, isTemplate. Know what each parameter represents.
3. isLoading check is critical. If a question describes an onChange script that should NOT run when the form first loads, the answer likely involves checking if (isLoading) return;.
4. onSubmit returns false to cancel. If a question asks how to prevent form submission based on validation, the answer is an onSubmit Client Script that returns false.
5. UI Policy vs. Client Script. If a question describes a simple requirement like making a field mandatory or read-only based on another field's value, the preferred answer is often UI Policy, not a Client Script. Only choose Client Script when the requirement involves complex logic, setting values, or manipulating the DOM.
6. Never use synchronous GlideRecord on the client. If an exam question presents code using GlideRecord in a Client Script, it is likely the wrong or suboptimal answer. The correct approach is GlideAjax with a client-callable Script Include.
7. g_form.getReference() with callback. Always use the callback version for better performance. The exam may present both versions and ask which is the best practice.
8. Execution order matters. Remember that UI Policies execute after Client Scripts. If a question asks why a Client Script's field attribute change is being overridden, the answer is likely a conflicting UI Policy.
9. Scope and table inheritance. Know that the Inherited checkbox determines whether the Client Script runs on child tables. Questions may test scenarios involving extended tables like Incident (extends Task).
10. Client Scripts do NOT fire on server-side operations. If a question mentions records being created via Import Sets, REST APIs, or Background Scripts, remember that Client Scripts will not execute in those contexts. Only Business Rules will fire.
11. Know key g_form methods. Be prepared to identify the correct g_form method for a given requirement: setValue, getValue, setMandatory, setVisible, setReadOnly, addErrorMessage, showFieldMsg, addOption, removeOption, clearOptions, and getReference.
12. Read questions carefully for UI Type. Some questions may specify whether the solution needs to work on the desktop, mobile, Service Portal, or both. The UI Type field on the Client Script controls this behavior.
13. Performance considerations. The exam values performance-conscious development. If given a choice between a client-side approach with server calls and a purely server-side approach, choose the option that minimizes unnecessary server round-trips while still meeting the requirement.
🎓 Unlock Premium Access
ServiceNow Certified Application Developer + ALL Certifications
- 🎓 Access to ALL Certifications: Study for any certification on our platform with one subscription
- 3305 Superior-grade ServiceNow Certified Application Developer practice questions
- Unlimited practice tests across all certifications
- Detailed explanations for every question
- CAD: 5 full exams plus all other certification exams
- 100% Satisfaction Guaranteed: Full refund if unsatisfied
- Risk-Free: 7-day free trial with all premium features!