Skip to main content
Known Participant
April 2, 2021
Question

How do I create a "Calculate Total" button?

  • April 2, 2021
  • 1 reply
  • 747 views

I am working on a form where I want the user to press a button to calculate the total after the series of fields have been entered.

 

So for example, there are five fields named Data.0, Data.1, Data.2, Data.3, Data.4

And a field named Total_Data and a button named Calculate_Sum. I don't want Total_Data to populate automatically as a running total. I want the user to enter values into the Data fields and then press Calculate_Sum at which point the script runs and the value appears in the Total_Data field.

 

In my actual form there are as many as 40 Data fields so obviously I don't want to write an entire script of

 

var a = this.getField("Data.0").value;

var b = this.getField("Data.1").value;

...... (etc.)

event.value = (a+b+c+...)

 

How do I script the Calculate_Sum button?

This topic has been closed for replies.

1 reply

ls_rbls
Community Expert
Community Expert
April 2, 2021

You can use this example to customize your current script:

 

  • Example Make a calculation of the values of the child fields of the parent field.

 

// f has 3 children: f.v1, f.v2, f.v3

 

var f = this.getField("f"); var a = f.getArray(); var v = 0.0; for (j =0; j < a.length; j++) v += a[j].value;

 

// v contains the sum of all the children of field "f"

 

The example above is a reference from the  JavaScript API JavaScript™ for Acrobat® API Reference Field methods, page 416

Nesa Nurani
Community Expert
Community Expert
April 2, 2021

Just to add that you need to convert it to a number or you can get incorrect results.