Reputation: 265
I have a PDF form that I'm making that adds up 5 fields with javascript.. The script will add all the numbers,but if one field is left blank the total is all screwed up. If I go back and add a zero to the blank field everything works fine. How can I fix this.
this.getField("RUNTOTAL").value = this.getField("RUNRow1").value + this.getField("RUNRow2").value + this.getField("RUNRow3").value + this.getField("RUNRow4").value + this.getField("RUNRow5").value;
OK so I tried this and it doesn't work at all now. Maybe I missed something?
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function getFieldValue(RUNRow1) {
var value = this.getField(RUNRow1).value;
return isNumeric(value) ? value : 0;
}
function getFieldValue(RUNRow2) {
var value = this.getField(RUNRow2).value;
return isNumeric(value) ? value : 0;
}
function getFieldValue(RUNRow3) {
var value = this.getField(RUNRow3).value;
return isNumeric(value) ? value : 0;
}
function getFieldValue(RUNRow4) {
var value = this.getField(RUNRow4).value;
return isNumeric(value) ? value : 0;
}
function getFieldValue(RUNRow5) {
var value = this.getField(RUNRow5).value;
return isNumeric(value) ? value : 0;
]
this.getField("RUNTOTAL").value = getFieldValue("RUNRow1") + getFieldValue("RUNRow2") + getFieldValue("RUNRow3") + getFieldValue("RUNRow4") + getFieldValue("RUNRow5");
Upvotes: 0
Views: 514
Reputation: 3605
This is a consequence of the loose typing of JavaScript. And it hits me every now and then. By default, JavaScript treats the empty string as string, and not as number 0, unless you persuade it to do so.
The simplest way would be multiplying every field value with 1 (which assumes that the fields do contain strings which can be converted to valid numbers).
Therefore, the code would look like this:
this.getField("RUNTOTAL").value = this.getField("RUNRow1").value*1 + this.getField("RUNRow2").value*1 + this.getField("RUNRow3").value*1 + this.getField("RUNRow4").value*1 + this.getField("RUNRow5").value*1;
Upvotes: 3