I have a function that when clicking on a button, it would add fields, each time it adds, it adds 3 fields, quantity, total value and subtotal value. My question is how would I change the total amount by changing quantity or value? These fields have n times. Just my question is in the Javascript / jQuery question, the database normally receives.
add_field () - Add fields such as product name, unit value, quantity, and total value
function add_field()
{
var f = $("#div_addfield");
f.append( '<br><hr><label for="nome_produto">Produto - ' + i + '</label> ' +
'<input id="nome_produto" type="text" name="data[OrdemCompra_itens][' + i + '][nome_produto]" class="form-control" /><br>' +
'<div class="form-inline">' +
'<label>Quant:</label>' +
' <input type="number" name="data[OrdemCompra_itens][' + i + '][quantidade]" min="1" value="1" ' +
' style="width:70px;" class="form-control quantidade" />' +
'<label>Vlr. Unit.:</label>' +
' <input type="text" name="data[OrdemCompra_itens][' + i + '][vlr_unit]" ' +
' style="width:100px;" class="form-control real vlr_unit" />' +
'<label>Vlr. Total.:</label>' +
' <input type="text" name="data[OrdemCompra_itens][' + i + '][vlr_total]" ' +
' style="width:120px;" class="form-control vlr_total" value="0,00" />' +
'</div><br>');
i++;
$(".real").maskMoney({showSymbol:true, symbol:"R$", decimal:",", thousands:"."});
}
calculate () responsible function to do the calculation, multiplying value by quantity
function calcula(vlr_unit, quant)
{
var res;
res = parseFloat(vlr_unit.replace(".", "").replace(",", ".")) * quant;
return parseFloat(res).toFixed(2).replace(".", ",");
}
Excerpt that the error is supposed to be
$(document).on('change', ".vlr_unit, .quantidade", function () {
$(".vlr_total").val(calcula($(".vlr_unit").val(), $(".quantidade").val()));
});
In this last part, it only changes the first field added
Last correction, so far all right, only solving the decimal question
$(document).on('change', ".vlr_unit, .quantidade", function () {
var subtotal = 0, total = 0;
$(".vlr_unit").each(function() {
var quantidade = $(this).siblings('.quantidade').val();
subtotal = calcula(this.value, quantidade);
total += parseFloat(subtotal.replace(",", "."));
$("#vlr_total").val(total);
$(this).siblings(".vlr_subtotal").val(subtotal);
});
});