Using the value from one field to populate another is covered throughout this guide. But because performing calculations and displaying the result is so basic to many user’s requirements, it is covered specifically here.
Before performing a calculation based on the contents of a field, you need to confirm that the field is not empty, and actually contains a value. Otherwise your script will generate an error. You do this by testing the field’s value with the tonumber() function.
The following example is quite typical. Changing the values within a number of fields, such as quantity and price, can cause the total to automatically update. To achieve this, you place the calculating code in the OnValidate event of the total field, and call the OnValidate event from the OnBlur event of the quantity and price fields. This method causes the value of the total to be updated as the user exits the fields that are involved in the calculation.
You should also check in case the user goes back to the field and subsequently removes a value. That is why in the example, the code not only enters the multiplication of the price by the quantity if values have been entered, but also places an empty string in the total field if no value is found.
You may wish to allocate Alias names to the fields involved in the calculations, to reduce the complexity of the script. It may also be useful to make the total fields ‘Read Only’ to prevent users from entering values directly.
Where possible, combine your script with the same events of an element. For example, if you have two pieces of script, one within the OnBlur event, and one in the OnValidate event, and these can both be effectively contained in the OnValidate event, then do so. Events have a processing overhead and reducing the number employed can speed up device input.