onChange client script: show and require a field conditionally
Show a field and make it mandatory only when another field has a specific value, and reset both cleanly when it changes back.
October 1, 2026 · #client-script #g_form #forms
A common form rule: when category is a certain value, ask for an extra detail. Try a UI Policy first; use a client script when the condition needs logic UI Policies can’t express.
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
var FIELD = 'u_hardware_asset_tag'; // the field to show and require
var needed = newValue === 'hardware';
g_form.setDisplay(FIELD, needed);
g_form.setMandatory(FIELD, needed);
if (!needed && !isLoading) {
g_form.clearValue(FIELD); // don't leave hidden data behind
}
}
How it works
- Runs on load and on every change of the watched field, so the form is always in the right state.
setMandatory(false)before hiding means a hidden field can never block saving.
Gotchas
- If a UI Policy can do it, prefer the UI Policy: it’s declarative and easier for admins to maintain.
- Make sure the field is on the form (it can be hidden by default); client scripts can’t show fields that aren’t there.
MIT licence. Provided as-is, without warranty. Test in a sub-production instance first.