Introduction

  • You might be aware of the calculation custom field.
  • It exists so that you can do custom calculations
  • However, its also possible to do calculations using JavaScript

Step-by-Step Instructions:

Step 1: In a Q&A node, add a script

Step 2: Give it a name, for type choose script, and set it to fire on exit of the node

Important: DT.setField function cannot be used on the last node for V2 DTs.

Inside the script section we can define our script.

For example:

<script>

//(1) Multiply two numbers
var answer1 = 5 * 5;   

//print answer on browser console ( CTRL + SHIFT + I )   
console.log( answer1 );   

//(2) Add two custom fields   
var answer2 = parseInt('{number1}') + parseInt('{number2}');
console.log( answer2 );   

//(3) Assign answer2 to a custom field   
DT.setField('score', answer2); 

</script>

In ( 1 ) We multiply two numbers and store the result in a JS variable called ‘answer1’

In ( 2 ) We add two LH custom fields and store the result in a JS variable called ‘answer2’.

  • Note than when using LH custom fields first we surround them with quotes.
  • And in a numerical calculation we need to parse them ( because they are printed as string textual values ). We do this using the parseInt() & parseFloat() functions.
  • The parseInt method is for whole numbers.
  • The parseFloat function is for decimal numbers.

In ( 3 ) We assign a LH custom field called ‘{score}’ the value of the JS variable ‘answer2’

  • Note that all custom fields must exist first. So we need to create {number1}, {number2}, and {score} in advance
  • Finally, you need to publish and test via the direct link. Because scripts don’t run in preview.