Calculate the sum of 3 fields and autopopulate total field
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-20-2022 08:07 AM
I have been trying to calculate the sum of 3 fields and auto-populate a total field with the following OnChange script:
var X = g_form.getValue('c1');
var Y = g_form.getValue('c2');
var Z = g_form.getValue('c3');
var xyz = parseInt(X) + parseInt(Y) + parseInt(Z);
g_form.setValue('total', xyz);
alert(xyz);
However, this isn't yielding any result but it is working with OnSubmit Client Script.
Can someone pls help me where I'm going with this?
- Labels:
-
Service Portal Development
- 1,880 Views
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-20-2022 08:34 AM
Hi,
so where are you writing the above script?
You are saying it's working in onSubmit but not where in which other script?
why not use before insert/update BR to set the value?
regards
Ankur
Ankur
✨ Certified Technical Architect || ✨ 9x ServiceNow MVP || ✨ ServiceNow Community Leader

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-20-2022 09:00 AM
If any of the fields are empty, the .getValue() method will return an empty string, not the number zero. As a result, when you try to parseInt( "" ), you get NaN. Try something like:
var x = g_form.getValue( 'c1' ) || 0;
var y = g_form.getValue( 'c2' ) || 0;
var z = g_form.getValue( 'c3' ) || 0;
var xyz = parseInt( x ) + parseInt( y ) + parseInt( z );
g_form.setValue( 'total', xyz );
alert(xyz);
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
06-21-2022 04:48 AM
Thank you very much for your valuable input. The script finally worked with your correction and also alongside using the same script for 3 variables as one more member Mr.Hitoshi Ozawa mentioned here!
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
08-15-2023 08:35 AM
Where did you create this script? Is this a business rule script, client script? I have a similar situation and this would be very helpful.
Thank you