Skip to Content

Dynamic Field Visibility

Show or hide fields based on another field's value (e.g., show "Other reason" field only when user selects "Other" from dropdown).

onChange Table: incident Field: category
#visibility #show-hide #conditional #onChange #onLoad

Script Code

JavaScript
1function onChange(control, oldValue, newValue, isLoading, isTemplate) {
2  // Configuration: Define visibility rules
3  // Key = field value that triggers showing fields
4  // Value = array of fields to show
5  var visibilityRules = {
6    'other': ['u_other_reason', 'u_other_details'],
7    'hardware': ['u_hardware_type', 'cmdb_ci'],
8    'software': ['u_application_name', 'u_software_version']
9  };
10
11  // Hide all conditional fields first
12  Object.keys(visibilityRules).forEach(function(key) {
13    visibilityRules[key].forEach(function(field) {
14      g_form.setDisplay(field, false);
15
16      // Optional: Clear the field when hiding
17      if (!isLoading) {
18        g_form.clearValue(field);
19      }
20    });
21  });
22
23  // Show fields based on current value
24  if (newValue && visibilityRules[newValue]) {
25    visibilityRules[newValue].forEach(function(field) {
26      g_form.setDisplay(field, true);
27    });
28  }
29}

How to Use

1. Create an onChange Client Script on your table 2. Set the field to your controlling field (e.g., category) 3. Customize the `visibilityRules` object with your field values and fields to show 4. Create a duplicate script as onLoad type with the same logic for initial form load

Explore More Scripts

Browse our complete library of ServiceNow scripts

View All Scripts