qs.defineNS('app'); app.IncomeCalculator = qs.createObject(); app.IncomeCalculator.prototype = { options: { formId: null, incrementElementsSelector: null, decrementElementsSelector: null, resultElementId: null }, incrementFields: null, decrementFields: null, sourceFields: null, resultField: null, initialize: function(options) { this.options = options; if (!this.options.formId || !this.options.resultElementId || !this.options.incrementElementsSelector || !this.options.decrementElementsSelector) { alert('Can not initialize Form'); } else { this.incrementFields = $('form#' + this.options.formId + ' ' + this.options.incrementElementsSelector); this.decrementFields = $('form#' + this.options.formId + ' ' + this.options.decrementElementsSelector); this.sourceFields = $('form#' + this.options.formId + ' ' + this.options.incrementElementsSelector + ', form#' + this.options.formId + ' ' + this.options.decrementElementsSelector ); this.resultField = $('form#' + this.options.formId + ' #' + this.options.formId + '-' + this.options.resultElementId); this.initSourceData(); this.showTotal(this.incrementFields, this.decrementFields); } }, initSourceData: function() { var source = this.sourceFields; var self = this; source.bind('change keyup input', function(){ self.showTotal(self.incrementFields, self.decrementFields); }); }, doCalculate: function (incrementFields, decrementFields) { var sum = 0, self = this; incrementFields.each(function() { var value = self._currencyToFloat($(this).val()); if (value) { sum += parseFloat(value); } }); decrementFields.each(function() { var value = self._currencyToFloat($(this).val()); if (value) { sum -= parseFloat(value); } }); return sum; }, _currencyToFloat: function(str) { return Number(str.replace(/[^0-9\.]+/g,"")); }, showTotal: function (incrementFields, decrementFields) { var total = this.doCalculate(incrementFields, decrementFields); if (total) { this.resultField.val( _.num.format(total,2)); } else { this.resultField.val(''); } } };