Skip to Content

Calculate Field Values Dynamically

Automatically calculate field values based on other fields (e.g., calculate total cost, days between dates, percentage).

onChange Table: incident Field: u_quantity
#calculation #onChange #dynamic #math #auto-calculate #total

Script Code

JavaScript
1function onChange(control, oldValue, newValue, isLoading, isTemplate) {
2  // Exit if form is loading
3  if (isLoading) {
4    return;
5  }
6
7  // Example 1: Calculate total cost (quantity × unit price)
8  var quantity = parseFloat(g_form.getValue('u_quantity')) || 0;
9  var unitPrice = parseFloat(g_form.getValue('u_unit_price')) || 0;
10  var totalCost = quantity * unitPrice;
11
12  // Set the calculated total with proper formatting
13  g_form.setValue('u_total_cost', totalCost.toFixed(2));
14
15  // Optional: Show currency formatted value
16  if (totalCost > 0) {
17    var formattedTotal = '$' + totalCost.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
18    g_form.showFieldMsg('u_total_cost', 'Total: ' + formattedTotal, 'info');
19  }
20
21  // Example 2: Calculate percentage
22  // Uncomment to enable
23  /*

24
25  // Example 3: Calculate days between dates
26  // Uncomment to enable
27  /*

28
29  // Example 4: Calculate discount and final price
30  // Uncomment to enable
31  /*

32
33  // Example 5: Calculate average
34  // Uncomment to enable
35  /*

36
37  // Example 6: Calculate age from date of birth
38  // Uncomment to enable
39  /*

40}
41    // Calculate difference in days
42    var diffTime = Math.abs(end - start);
43    var diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
44
45    g_form.setValue('u_duration_days', diffDays);
46    g_form.showFieldMsg('u_duration_days', diffDays + ' days between dates', 'info');
47  }
48  */
49
50  // Example 4: Calculate discount and final price
51  // Uncomment to enable
52  /*
53  var originalPrice = parseFloat(g_form.getValue('u_original_price')) || 0;
54  var discountPercent = parseFloat(g_form.getValue('u_discount_percent')) || 0;
55
56  var discountAmount = originalPrice * (discountPercent / 100);
57  var finalPrice = originalPrice - discountAmount;
58
59  g_form.setValue('u_discount_amount', discountAmount.toFixed(2));
60  g_form.setValue('u_final_price', finalPrice.toFixed(2));
61  */
62
63  // Example 5: Calculate average
64  // Uncomment to enable
65  /*
66  var value1 = parseFloat(g_form.getValue('u_value_1')) || 0;
67  var value2 = parseFloat(g_form.getValue('u_value_2')) || 0;
68  var value3 = parseFloat(g_form.getValue('u_value_3')) || 0;
69
70  var average = (value1 + value2 + value3) / 3;
71  g_form.setValue('u_average', average.toFixed(2));
72  */
73
74  // Example 6: Calculate age from date of birth
75  // Uncomment to enable
76  /*
77  var dob = g_form.getValue('u_date_of_birth');
78  if (dob) {
79    var birthDate = new Date(dob);
80    var today = new Date();
81
82    var age = today.getFullYear() - birthDate.getFullYear();
83    var monthDiff = today.getMonth() - birthDate.getMonth();
84
85    if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birthDate.getDate())) {
86      age--;
87    }
88
89    g_form.setValue('u_age', age);
90  }
91  */
92}

How to Use

1. Create onChange Client Scripts for relevant fields (quantity, price, dates, etc.) 2. Customize the calculation logic for your use case 3. Update field names to match your table structure 4. Uncomment additional calculation examples as needed 5. Consider adding the same script to onLoad to calculate values when form opens 6. Test with various numeric values and edge cases (zero, negative, decimals)

Explore More Scripts

Browse our complete library of ServiceNow scripts

View All Scripts