← Script library

Client Scripts

Auto-populate Related Fields

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

JavaScript
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
  // Exit if the form is loading to avoid unnecessary queries
  if (isLoading || newValue === '') {
    return;
  }

  // Configuration: Map source fields to target fields
  // Change these field names to match your requirements
  var fieldsToPopulate = {
    'phone': 'phone',           // caller_id.phone -> phone
    'email': 'email',           // caller_id.email -> email
    'location': 'location',     // caller_id.location -> location
    'department': 'department'  // caller_id.department -> department
  };

  // Get reference field value (caller_id in this example)
  var caller = g_form.getReference('caller_id', function(ref) {

    // Loop through each field mapping
    for (var sourceField in fieldsToPopulate) {
      var targetField = fieldsToPopulate[sourceField];

      // Get the value from the reference record
      var value = ref[sourceField];

      // Only set the field if it's empty (to avoid overwriting user input)
      if (value && g_form.getValue(targetField) === '') {
        g_form.setValue(targetField, value);
      }
    }
  });
}

How to use it

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

Adapt the table names, fields, and conditions to your instance. Test the behavior in a development environment before using it in production.