When remove the value in a field for client script onChange

ESL
ServiceNow Employee
ServiceNow Employee

I created a client script that calculates the sum of the values of some fields. If I put some value in thees fields, the total value is calculated immediately.
However, if I delete the value of one of the fields, the total value will not be reflected immediately, if I do not update the value of the other fields, the correct total value will not be reflected.
But when I change the value to 0 instead of deleting it, there is no such problem. Is there any workaround?

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    //Type appropriate comment here, and begin script below
    var h2 = g_form.getDecimalValue('u_float_23');
    if (h2 === '') {
        return;
    }
    var h3 = g_form.getDecimalValue('u_float_24');
    if (h3 === '') {
        return;
    }
    var h4 = g_form.getDecimalValue('u_float_25');
    if (h4 === '') {
        return;
    }
    var h5 = g_form.getDecimalValue('u_float_26');
    if (h5 === '') {
        return;
    }
    var h6 = g_form.getDecimalValue('u_float_28');
    if (h6 === '') {
        return;
    }
    var h7 = g_form.getDecimalValue('u_float_27');
    if (h7 === '') {
        return;
    }



     var total = parseInt(newValue, 10) + parseInt(h2, 10) + parseInt(h3, 10) + parseInt(h4, 10) + parseInt(h5, 10) + parseInt(h6, 10) + parseInt(h7, 10);

    g_form.setValue('u_float_21', total);
}
1 ACCEPTED SOLUTION

Jaspal Singh
Mega Patron
Mega Patron

Insted of simply using return;

can you try

if (h2 === '') { h2=0; }

& so-on

View solution in original post

3 REPLIES 3

Jaspal Singh
Mega Patron
Mega Patron

Insted of simply using return;

can you try

if (h2 === '') { h2=0; }

& so-on

However, if I delete the value of one of the fields, the total value will not be reflected immediately, if I do not update the value of the other fields, the correct total value will not be reflected.

Is because you need client script for each field where you enter decimal value.

Sebastian L
Mega Sage
Well you have a return if you have no decimal value, so your script will not reach the calculations because it has no value. Also, just a thought, could it be an idea to look into a calculated field instead of doing it on change? Of course only if it is a form ????

Best regards,
Sebastian Laursen