Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Calculate total cost and set in variable using catalog client script

Rajavardhini
Tera Contributor

Hi Team,

I have 4 different variables to enter the cost.

Onchange each variable calculate the total field and update in the total cost.

I have written below code but throwing NAN error.

 

function onChange(control, oldValue, newValue, isLoading) {
    if (isLoading || newValue == '') {
        return;
    }
    var numnericVal = g_form.getValue('estimated_cost_rail_update');

    if (isNaN(numnericVal)) // check if value is not numeric

    {


        g_form.setValue('estimated_cost_rail_update', ''); // Set the field to empty
        g_form.showFieldMsg('estimated_cost_rail_update', 'Please enter numeric values', 'error');


    } else {
        var estimated_air = g_form.getValue("estimated_cost_air");
        var estimated_rail = g_form.getValue("estimated_cost_rail_update");
        var estimated_car = g_form.getValue("estimated_cost_taxi_upate");
        var estimated_hotel = g_form.getValue("estimated_cost_hotel_update");

        var total=parseInt(estimated_air)+parseInt(estimated_rail)+parseInt(estimated_car)+parseInt(estimated_hotel);
       
        //var total = parseFloat(estimated_air) + parseFloat(estimated_rail) + parseFloat(estimated_car) + parseFloat(estimated_hotel);
        g_form.setValue("estimated_cost3", total);
        alert(parseInt(total));
    }

    //Type appropriate comment here, and begin script below

}
 
Please help if any mistake is here.
 
Regards,
Vardhini
1 REPLY 1

Najmuddin Mohd
Mega Sage

Hi @Rajavardhini ,

 

I have checked this. Yes, this issue happens when you changing the field values on which you have written on-change client script and other field values are empty.

To avoid this, I had retrieved values as Zero(0), if the field values are empty else take the value present in it.

var estimated_air = (g_form.getValue("estimated_cost_air") != '') ? g_form.getValue('estimated_cost_air') : 0;

Use the above ternary operation for all the values.

If this information helps you, Kindly mark this post as Helpful and Accept the solution.

Regards,
Najmuddin.