Aqui está um exemplo de soma de 3 inputs, conforme o usuário vai digitando ele já vai calculando total, como mostra o exemplo abaixo:
<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>
O código javaScript é este:
$('[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) : "");
};