Behavior: Calculate

Overview

The Calculate behavior is sugar for calculating a form element based on the values of other form elements. For example, Project.Timesheet.Edit.xslt includes UnitCount, Rate and AmountMoney fields, where AmountMoney = UnitCount * Rate.

<form>
  <input type="text" id="UnitCount"/>
  <input type="text" id="Rate"/>
  <input type="text" id="AmountMoney" data-behavior="Calculate" data-calculate-options="{{'depends': 'UnitCount,Rate', 'calculate': 'multiply'}}" />
</form>

This is simply more concise than:

<form>
  <input type="text" id="UnitCount" onchange="calculateAmount();"/>
  <input type="text" id="Rate" onchange="calculateAmount();"/>
  <input type="text" id="AmountMoney" />
  <script type="text/javascript">
function calculateAmount()
{
  document.id('AmountMoney').value = "";
  if (!isNaN(document.id('UnitCount').value) && !isNaN(document.id('Rate').value)) {
    document.id('AmountMoney').value = parseFloat(document.id('UnitCount').value) * parseFloat(document.id('UnitCount').value);
  }
}
  </script>
</form>

Behavior Options

Options for the Calculate behavior comprise:
  • depends (String, required): comma-separated list of element id's to consider in the calculation
  • defaultValue (String, defaults to ''): default value to set if there are not enough values to perform the calculation
  • calculate (String, defaults to 'sum'): name of the calculation function defined in the qbo3.Calculator object
The qbo3.Calculator object is used to define calculation functions; by default it contains 'sum' and 'multiply'.  If you need more complex calculation logic, you can implement as follows:

qbo3.Calculator = Object.merge(qbo3.Calculator || {}, {
myCalc: function (element, depends, options) { ... }
});

and then reference it with:

<input type="text" id="AmountMoney" data-behavior="Calculate" data-calculate-options="{{'depends': 'UnitCount,Rate', 'calculate': 'myCalc'}}" />

See qbo.ApplicationWeb > Scripts > qbo.Math.js for the behavior, including the definition of sum and multiply in the qbo3.Calculator object.
Comments