# jQuery Calculation Plug-in (v0.1)

The Calculation plug-in is designed to give easy-to-use jQuery functions for commonly used mathematical functions.

This plug-in will work on all types of HTML elements—which means you can use it to calculate values in <td> elements or in <input> elements. You can even mix and match between element types.

Numbers are parsed from the element using parseNumber() method—which uses a regular expression (`/(-?\\$?)(\d+(,\d{3})*(\.\d{1,})?|\.\d{1,})/g`) to parse out the numeric value. You can change the regular expression that's used to determine what's consider a number by changing the default regular expression.

If you're page is using European-style formatting (i.e. 1.000,00) you'll need to change the default parsing handlers for European formatting. The calculation plug-in should be powerful enough to address any style formatting your numbers might be in. For US-style formatting, no changes are needed (it assumes numbers are in the format 1,000.00).

jquery.calculation.js
jquery.calculation.min.js

## Interactive Examples

Calculation Examples

The Calculation plug-in can parse various DOM elements. From normal `div` and `span` tags to all form field elements.

Numbers:    Sum: (Change the values for dynamic calculations.)

Numbers:    Average: (Change the values for dynamic calculations.)

NOTE: The above example uses the onParseError and onParseClear methods to change the background of any field in which it can not correctly parse the number from. To test this, try changing a field to all numeric values.

Numbers:    Min: (Change the values for dynamic calculations.)

Numbers:    Max: (Change the values for dynamic calculations.)

Numbers: -\$19.99 + -\$7.99 + -\$.99 + -\$49.99    Sum: ????

Numbers: 3,294.75 + 85.97 + 2974.25 + \$6,502.03    Avg: ????

The example below shows how the calculation plug-in can be used to dynamically calculate values for you. All of the "Total" values (including the "Grand Total") are calculated automatically using the calc() method.

Qty Product Price Total
Learning jQuery \$39.99 \$39.99
jQuery Donation \$14.99 \$14.99
Grand Total:

## Syntax Examples

• `\$("input[name^='price']").parseNumber();`
This would return an array of potential number for every match in the selector
• `\$("input[name^='sum']").sum();`
Returns the sum of all the input objects that start with a name attribute of "sum". This breaks the jQuery chain.
• `\$("input[name^=';sum']").sum("keyup", "#totalSum");`
Updates the "#totalSum" element with the sum of all the input objects that start with the name attribute of "sum" anytime the keyup event occurs within those fields. This does not break the jQuery chain.
• `\$("input[name^='avg']").avg();`
Returns the average of all the input objects that start with a name attribute of "avg".
• `\$("input[name^='avg']").avg("keyup", "#totalAvg");`
Updates the "#totalAvg" element with the average of all the input objects that start with the name attribute of "avg" anytime the keyup event occurs within those fields. This does not break the jQuery chain.
• ``````\$("input[name^='avg']").avg({
bind: "keyup"
, selector: "#totalAvg"
, oncalc: function (value, settings){
// you can use this callback to format values
\$(settings.selector).html("\$" + value);
}
});``````
Updates the "#totalAvg" element with the average of all the input objects that start with the name attribute of "avg" anytime the keyup event occurs within those fields. This uses the oncalc callback to format the results by appending a "\$" to front of the value. This does not break the jQuery chain.
• `\$("input[name^='min']").min();`
Returns the minimum value of all the input objects that start with a name attribute of "min".
• `\$("input[name^='max']").max();`
Returns the maximum value of all the input objects that start with a name attribute of "max".
• ``````\$("[id^=total_item]").calc(
// the equation to use for the calculation
"qty * price",
// define the variables used in the equation, these can be a jQuery object
{
qty: \$("input[name^=qty_item_]"),
price: \$("[id^=price_item_]")
},
// define the formatting callback, the results of the calculation are passed to this function
function (s){
// return the number as a dollar amount
return "\$" + s.toFixed(2);
},
// define the finish callback, this runs after the calculation has been complete
function (\$this){
// sum the total of the \$("[id^=total_item]") selector
var sum = \$this.sum();

\$("#grandTotal").text(
// round the results to 2 digits
"\$" + sum.toFixed(2)
);
}
);``````
This example shows off the code used quantity * price = total example shown above.
• ``````\$.Calculation.setDefaults({
// regular expression used to detect numbers, if you want to force the field to contain
// numbers, you can add a ^ to the beginning or \$ to the end of the regex to force the
// the regex to match the entire string: /^(-|-\\$)?(\d+(,\d{3})*(\.\d{1,})?|\.\d{1,})\$/g
reNumbers: /(-|-\\$)?(\d+(,\d{3})*(\.\d{1,})?|\.\d{1,})?/g
// should the Field plug-in be used for getting values of :input elements?
, useFieldPlugin: true/false
// a callback function to run when an parsing error occurs
, onParseError: null
// a callback function to run once a parsing error has cleared
, onParseClear: null
});``````
Use the setDefaults() method to change the default parameters for the Calculation Plug-in. If the Field Plug-in is loaded, then it will be used by default.

• For european formatting (i.e. 1.000,00) set the following defaults:
``````\$.Calculation.setDefaults({
// a regular expression for detecting European-style formatted numbers
reNumbers: /(-?\\$?)(\d+(\.\d{3})*(,\d{1,})?|,\d{1,})/g
// define a procedure to convert the string number into an actual usable number
, cleanseNumber: function (v){
// cleanse the number one more time to remove extra data (like commas and dollar signs)
// use this for European numbers: v.replace(/[^0-9,\-]/g, "").replace(/,/g, ".")
return v.replace(/[^0-9,\-]/g, "").replace(/,/g, ".");
}
})``````
Use the setDefaults() method to change the default parameters for the Calculation Plug-in. If the Field Plug-in is loaded, then it will be used by default.