I'm having trouble letting the multiplication of quantity * price in a dynamically created table.
Better to explain, is to show. Here is the code in jsfiddle: link
HTML
<div class="container">
<div class="row">
<h3>Produtos</h3>
<table id="details-table" class="table">
<tbody>
<tr>
<th scope="col" class="col-1">Item</th>
<th scope="col" class="col-5">Produto</th>
<th scope="col" class="col-1">Quantidade</th>
<th scope="col" class="col-2">Preço</th>
<th scope="col" class="col-3">Total</th>
</tr>
</tbody>
</table>
</div>
<!-- #detail-details -->
<div class="form-group">
<button class="btn btn-primary" type="button" id="btn-add-item">Novo Item</button>
<input class="btn btn-success" type="submit" value="Salvar">
</div>
</div>
jQuery
(function ($) {
var counter = 0;
addRow = function () {
var table = $('#details-table');
var input = null;
var row = $('<tr class="linha">');
var cols = [];
counter++;
// Coluna 1 - Item
input = $('<input>').addClass('form-control').attr('name', 'item' + counter + '').val(counter).attr('disabled', 'disabled');
cols.push(
$('<td>').append(
$('<div>').addClass('form-group').append(input)
)
);
// Coluna 2 - Produto
input = $('<input>').addClass('form-control').attr('name', 'produto' + counter + '');
cols.push(
$('<td>').append(
$('<div>').addClass('form-group').append(input)
)
);
// Coluna 3 - Quantidade
input = $('<input>').addClass('form-control').attr('name', 'quantidade' + counter + '');
cols.push(
$('<td>').append(
$('<div>').addClass('form-group').append(input)
)
);
// Coluna 4 - Preço
input = $('<input>').addClass('form-control').attr('name', 'preco' + counter + '');
cols.push(
$('<td>').append(
$('<div>').addClass('form-group').append(input)
)
);
// Coluna 5 - Total
input = $('<input>').addClass('form-control').addClass('total').attr('name', 'total' + counter + '').val(totalPreco).attr('disabled', 'disabled');
cols.push(
$('<td>').append(
$('<div>').addClass('form-group').append(input)
)
);
// Button Remove
cols.push(
$('<td>').addClass('actions').append(
$('<button>').addClass('btn btn-danger btn-remove-item').html('×').attr('type', 'button').on('click', removeRow)
)
);
row.append(cols);
table.append(row);
return false;
}
totalPreco = function () {
$('input[name="total'+counter+'"]').on('keyup', function(){
var quantidade = $('input[name="quantidade'+counter+'"]').val();
var preco = $('input[name="preco'+counter+'"]').val()
var total = $('input[name="total'+counter+'"]');
var precoTotal = parseFloat(quantidade) * parseFloat(preco);
return precoTotal;
});
}
removeRow = function () {
$(this).closest('.linha').remove();
return false;
}
$('#btn-add-item').click(addRow);
})(jQuery);
Thanks in advance!