Search code examples
javascriptpdfacrobat

How to calculate fields in Acrobat PDF using Javascript?


Calculating fields Acrobat pdf Javascript the total amount displays incorrectly when I skip a field but It works correctly when each field has a value from top to down. What is wrong?

var fields = this.getField("amount");
var a = fields.getArray();
var sum = 0;
for (i = 0; i < a.length; i++){
sum += a[i].value;

//I tried to place zeros in the fields if there are no values
if (fields.value == null){
   fields.value = 0;
}
}
//This code accept the total amount and also hides the default zeros 
if (sum > 0){
    event.value = sum;
}

else {
    event.value = "";
}



Incorrect

This works


Solution

  • To fixed this, Javascript Addition operator ``+``` can also be used to add (concatenate) strings. The empty field was acting as string so you will need to escape the string by appending + to the values.

    sum += +a[i].value;

    It is the same as var fields = +this.getField("amount");