Here is an example of the sum of 3 inputs, as the user is typing he is already calculating total, as shown in the example below:
<div id="qtde_elementos">
<form action="" method="post">
<div>
<label>Valor 1:</label>
<input data-id="0" class="qtde" type="number" placeholder="0" size="1" maxlength="2" max="10" min="0" step="0">
</div>
<div>
<label>Valor 2:</label>
<input data-id="1" class="qtde" type="number" placeholder="0" size="1" maxlength="2" max="10" min="0" step="0">
</div>
<div>
<label>Valor 3:</label>
<input data-id="2" class="qtde" type="number" placeholder="0" size="1" maxlength="2" max="10" min="0" step="0">
</div>
</form>
</div>
<div class="total" data-total>Total: <span>R$ 0,00</span>
</div>
The Java code is this:
$('[data-id]').change(function () {
var data = {
id: $(this).data('id'),
value: $(this).val()
}
$('body').trigger('total.update', [data]);
});
(function () {
var Total = function (el) {
this.$el = el;
this.value = 0;
this.products = new Array();
$('body').on('total.update', $.proxy(this, 'update'));
}
Total.prototype.update = function (e, data) {
this.products[data.id] = data.value
this.value = this.products.reduce(this.reduce);
this.render.apply(this);
}
Total.prototype.reduce = function (prev, current) {
return parseFloat(current) + parseFloat(prev);
}
Total.prototype.render = function () {
this.$el.find('span').html(currencyFormatted(parseFloat(this.value), 'R$'));
}
$(document).ready(function () {
$el = $('[data-total]');
var instance = $el.data('total-instance') || new Total($el);
$el.data('total-instance', instance);
});
})();
function currencyFormatted(value, str_cifrao) {
return str_cifrao + ' ' + value.formatMoney(2, ',', '.');
}
Number.prototype.formatMoney = function (c, d, t) {
var n = this,
c = isNaN(c = Math.abs(c)) ? 2 : c,
d = d == undefined ? "." : d,
t = t == undefined ? "," : t,
s = n < 0 ? "-" : "",
i = parseInt(n = Math.abs(+n || 0).toFixed(c)) + "",
j = (j = i.length) > 3 ? j % 3 : 0;
return s + (j ? i.substr(0, j) + t : "") + i.substr(j).replace(/(\d{3})(? =\d)/g, "$1" + t) + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : "");
};
And what is the doubt/problem?
– DontVoteMeDown