Calculated fields

Calculated Fields allow you to generate responses based on inputs to other fields within a form. Calculated Field calculations are written in Javascript, which means you can add some fairly complex logic to your calculations if you so wish, but good knowledge of Javascript (Typescript specifically) is required.

Calculated fields should always return a value, whether that is a number from a calculation (as we demonstrate below), some text, a date or any of the other options Coreo allows in this question type.

Example – calculating an area

As a simple example, we will take a form which has two Numeric Answer questions – a length and a width. We can automatically calculate the area by multiplying the length and width together. We will also round the answer to two decimal places.

The Numeric Answer questions will look like:

Numeric question

Both Number Answer questions must be mandatory, as answers are required for your Calculated Field to work.

Adding a calculated fields question

Fill in the question name, answer labels, etc as usual. You are then asked to select a display type.

In this case, we want a ‘Number’ display type, as we will be calculating a number type value from the other Numeric Answer questions. The Display Type must match the ‘type’ returned by the calculation, else no value will be returned. E.g. a Display Type of ‘Text’ when the returned value is a number will not work. The Calculated Field question will look like this:

Calculated fields question

The calculated fields code editor

Selecting ‘Manage Calculation’ takes you to the code editor as follows:

Calculated fields editor

The text area with the ‘1’ is where you type in your Javascript code. Initially, this will be blank. On the right hand side are the available fields from your form that are available to use in your calculation. In this example, we are interested in $length and $width. At the bottom of the area you can test your code by entering values in the boxes and pressing ‘Test Expression’ to check the result.

In this example, we want to calculate the area from the values submitted, so we will add some code to calculate the result of $length * $width, round it to two decimal places, and return it. Text beginning with // double slashes are comments which are helpful to explain your code to other users.

Calculated fields editor example code

We can add values to $length and $width and use ‘Test Expression’ to check the result before saving. Remember to save your form when you’re finished editing.

When viewing these questions in the Coreo app, you will see the questions as defined, and the Calculated Fields answer will adjust in real-time as you change the answers in the other two questions.

Calculated fields rendered in the app

When the record is submitted, you will get all three values in the record – length, width and area.

Calculated fields record view
Was this article helpful?