Skip to Content

Auto-populate Related Fields

Automatically populate fields when a reference field changes (e.g., populate caller's phone and email when caller is selected).

onChange Table: incident Field: caller_id
#reference-field #auto-populate #form #onChange

Script Code

JavaScript
1function onChange(control, oldValue, newValue, isLoading, isTemplate) {
2  // Exit if the form is loading to avoid unnecessary queries
3  if (isLoading || newValue === '') {
4    return;
5  }
6
7  // Configuration: Map source fields to target fields
8  // Change these field names to match your requirements
9  var fieldsToPopulate = {
10    'phone': 'phone',           // caller_id.phone -> phone
11    'email': 'email',           // caller_id.email -> email
12    'location': 'location',     // caller_id.location -> location
13    'department': 'department'  // caller_id.department -> department
14  };
15
16  // Get reference field value (caller_id in this example)
17  var caller = g_form.getReference('caller_id', function(ref) {
18
19    // Loop through each field mapping
20    for (var sourceField in fieldsToPopulate) {
21      var targetField = fieldsToPopulate[sourceField];
22
23      // Get the value from the reference record
24      var value = ref[sourceField];
25
26      // Only set the field if it's empty (to avoid overwriting user input)
27      if (value && g_form.getValue(targetField) === '') {
28        g_form.setValue(targetField, value);
29      }
30    }
31  });
32}

How to Use

1. Create an onChange Client Script on your table 2. Set the field name to the reference field you want to monitor 3. Customize the `fieldsToPopulate` object with your field mappings 4. Save and test on a form

Explore More Scripts

Browse our complete library of ServiceNow scripts

View All Scripts