Catalog Client Script: Trying to calculate 7 variables by Multiplying 5 then Add 2

User339333
Tera Contributor

In this script I'm trying to multiply the value of 5 variables and then add the value of 2 then place the answer in another field. My client script below is working correctly for the multiplication but the addition is being ignored. What am I doing wrong. 

 

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}
//Get Value of the followig select box variables and then multiply f1 - f5 + f6 + f7

var f1 = g_form.getValue('frequency');

var f2 = g_form.getValue('human_impact');

var f4 = g_form.getValue('existing_control_measures');

var f5 = g_form.getValue('organizational_impact');

var f6 = g_form.getValue('probability_of_success');

var f7 = g_form.getValue('rigor_of_evaluation_plan');

var f8 = g_form.getValue('trainee_included');

var f9 = f7 + f8;

var f3 = (f9) + (f1 * f2 * f4 * f5 * f6);

g_form.setValue("impact_score", f3);
//Type appropriate comment here, and begin script below

1 ACCEPTED SOLUTION

-O-
Kilo Patron
Kilo Patron

The + operator is both a numeric addition and a string concatenation. When one of the operant is a string, the operator will be the latter (string concatenation). And g_form.getValue() returns (only) strings. To fix it, you need to convert all those values to numbers before adding. E.g:

var f7 = +g_form.getValue('rigor_of_evaluation_plan');
var f8 = +g_form.getValue('trainee_included');
var f9 = f7 + f8;

The multiplication operator only works as such. It will try to convert non-numeric values to numbers before executing the operation. So if all those fields/variables contain valid numbers, those will be converted to numbers and will be multiplied - that is what that part is working.

View solution in original post

3 REPLIES 3

-O-
Kilo Patron
Kilo Patron

The + operator is both a numeric addition and a string concatenation. When one of the operant is a string, the operator will be the latter (string concatenation). And g_form.getValue() returns (only) strings. To fix it, you need to convert all those values to numbers before adding. E.g:

var f7 = +g_form.getValue('rigor_of_evaluation_plan');
var f8 = +g_form.getValue('trainee_included');
var f9 = f7 + f8;

The multiplication operator only works as such. It will try to convert non-numeric values to numbers before executing the operation. So if all those fields/variables contain valid numbers, those will be converted to numbers and will be multiplied - that is what that part is working.

User339333
Tera Contributor

Thank you kindly for clearing up my confusion. I've made the necessary adjustments that you suggested and it's working!

You're most welcome 🙂

Also the last bit should have been

that is whay that part is working

not

that is what that part is working.