subtract two currency fields and stored in currency fields

chandan86patra
Tera Contributor

Hi all ,

 

 

Write an onChange Client Script to subtract the values of two currency fields and store the result in another currency field.
 
I have tried :
 
 

var amountA = parseFloat(g_form.getValue('u_amount_a')) ;
var amountB = parseFloat(g_form.getValue('u_amount_b')) ;

var result = amountA - amountB;

g_form.setValue('u_result', result);

 

Answer is coming in the output NAN .

 

Could you please help me on this 

 

 

Thanks and Regards,

Chandan

1 ACCEPTED SOLUTION

Aditya_hublikar
Giga Sage

Hello @chandan86patra ,

 

 

Try this  :

function onChange(control, oldValue, newValue, isLoading, isTemplate) {

    if (isLoading) {
        return;
    }

    var a = parseFloat(g_form.getDecimalValue('u_a')) || 0;
    var b = parseFloat(g_form.getDecimalValue('u_b')) || 0;

    var total = a + b;

    g_form.setValue('u_c', total.toFixed(2));
}

 

Aditya_hublikar_0-1795178143666.png

 

 

If this helps you then mark it as helpful and accept as solution .

Regards,

Aditya

View solution in original post

5 REPLIES 5

alialkhayat
ServiceNow Employee

Hi Chandan

 

It looks like your u_amount_a and u_amount_b fields are showing a value like “USD;8”.

 

To get started, you’ll want to parse this so you can create a function to handle it.

 

Make sure both fields have values before proceeding.

 

Once you have the values, subtract them from each other and store the result in the Result field.

 

Here’s a sample code to help you get started:

 

function getAmount(values) {
        if (!values) {
            return null;
        }
        var parts = values.split(';');
        var num = parseFloat(parts[parts.length - 1].replace(/,/g, ''));
        return isNaN(num) ? null : num;
    }

    var a = getAmount(g_form.getValue('u_amount_a'));
    var b = getAmount(g_form.getValue('u_amount_b'));

    if (a === null || b === null) {
        g_form.clearValue('u_result');
        return;
    }

    g_form.setValue('u_result', (a - b).toFixed( 2 ));

Just a heads-up if you’re hoping to see changes in either field, you’ll need to set up two OnChange events. One for each Amount field, but make sure to use the same client script for both.

 

I hope this helps

 

Ali