Calculate the sum of 3 fields and autopopulate total field

Snehita katta
Mega Contributor

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?  

 

9 REPLIES 9

Ankur Bawiskar
Tera Patron
Tera Patron

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

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

John Dahl
Tera Guru

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);

 

 

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!  

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