Adding two number fields together with script (outside repeat)

Using a common ‘function’

The value of two number fields can be added together using the following common script function:

function dosum(){
    
    var val1 = parseInt(fld('FIELD_1002').val()) || 0;
    var val2 = parseInt(fld('FIELD_1003').val()) || 0;
    
    var sum = val1 + val2;
    
    fld('FIELD_1004').val(sum);
    
}

The parseInt() function turns a ‘string’ into a ‘number’ so that it can be used in a mathematical equation.

What this script is saying is: if the field is a number (i.e. an integer), then use the number ‘OR’ (i.e. ||) if the field is not an integer or is empty, then use the number ‘0’. This ensures that the add function works.

Another way of doing exactly the same thing would be to use the following function:

function dosum(){
    
    var val1 = isNaN(parseInt(fld('FIELD_1002').val())) ? 0 : parseInt(fld('FIELD_1002').val());
    var val2 = isNaN(parseInt(fld('FIELD_1003').val())) ? 0 : parseInt(fld('FIELD_1003').val());
    
    var sum = val1 + val2;
    
    fld('FIELD_1004').val(sum);
    
}

The isNan() functions tests to see if the field values are ‘not-a-number’. If the field is not a number, then it is assigned the value of ‘0’, otherwise the integer value is used.

The parseInt() function turns a ‘string’ into a ‘number’ so that it can be used in a mathematical equation.

You need to copy this script function into the Form Script Editor for your form. This is the best place to put a function so that it can be used by a number of fields within your form.

You then need to put a small bit of script in the Field Script Editor of each of the fields that are being added up, so that the add function is fired each time someone makes a change to the value of the field. The script you put in each field is:

dosum();

Achieving the same thing without a function

If you don’t want to use a function, then you can simple copy the following script into the Field Script Editor for each of the fields you want to add together. Given that the same script is in each field, it will be fired (and perform the calculation) each time the value in either field is changed. This way of doing things is probably OK if you are only adding two or so fields together, but when you start adding more than that, it becomes more efficient to use the common function, as per above:

var val1 = isNaN(parseInt(fld('FIELD_1002').val())) ? 0 : parseInt(fld('FIELD_1002').val());
var val2 = isNaN(parseInt(fld('FIELD_1003').val())) ? 0 : parseInt(fld('FIELD_1003').val());

var sum = val1 + val2;
fld('FIELD_1004').val(sum);

Adding fields within a repeat table

If you want to add numbers within a repeating table with script, then read this article.