This example shows how to provide two calculated fields on an Add or Edit screen layout. This could be achieved by using business rules, but this examples serves the purpose of showing alternative methods of achieving similar results. The key difference is that business rules are executed via an Ajax call back to the server, while the JavaScript approach downloads the code to the client browser where it is executed.

The example involves two fields named VAL1 and VAL2. Numeric data entered into these two fields will be summed and the result placed in a third field named VAL_SUM, and the two fields will be multiplied and the result placed in a fourth field named VAL_PRODUCT. All four fields have a display type of Number. To set up this requirement, take the following steps –

  • Within the data dictionary, define the fields VAL1, VAL2, VAL_SUM and VAL_PRODUCT, all with a display type of Number
  • Make sure you give these fields read and write permission
  • Place all the fields on an Add or Edit screen layout. Add an HTML modifier to the fields named VAL1 and VAL2. The modifier value should be onchange=calc();
  • Place the following JavaScript functions within the UserJavaScript.js file. Note that the field names referenced in the layout have p_ prefixed to their names. These are the parameter names of the fields

    function valOf(which) {
      if (! which) return 0;
        var val = parseInt(which, 10);
      if (isNaN(val)) return 0;
        return val;
    }
    
    function calc() {
      document.editForm.p_val_product.value =
                        document.editForm.p_val1.value * 
                        document.editForm.p_val2.value;
      var a = document.editForm.p_val1.valueOf;
      document.editForm.p_val_sum.value =
                        valOf(document.editForm.p_val1.value) + 
                        valOf(document.editForm.p_val2.value);
      return;
    }
  • When the user changes either the field named VAL1 or VAL2, the JavaScript function is triggered, and the results are immediately displayed in VAL_SUM and VAL_PRODUCT.