Reputation: 378
I have a function to add elements to a table which is:
$('#mais').on('click', function(){
var next = $('#lista tbody').children('tr').length + 1;
$(':input[name="qtd_itens"]').val(next);
$('#lista tbody').append('<tr>' +
'<td><input type="text" name="qtd' + next + '" size="5" /></td>' +
'<td><input type="text" name="unidade' + next + '" size="6" /></td>' +
'<td><input type="text" name="mercadoria' + next + '" size="20" /></td>' +
'<td><input type="text" name="codigo' + next + '" size="15" /></td>' +
'<td><input type="text" name="preco' + next + '" size="10" class="money" /></td>' +
'<td><input type="text" name="total' + next + '" size="10" readonly /></td>' +
'<th><a href="#" id="menos"><img src="imgs/delete.png" height="20px" width="20px"></a></th>' +
'</tr>');
$('.money').maskMoney({thousands:'.', decimal:','});
return false;
});
An i tried to do the remove function but i couldn't be able.
I have tried :
$('#menos').on('click', function(){
$('#lista tbody').children('tr:last').remove();
$(':input[name="qtd_itens"]').val() -= 1;
});
But it's not working. Can someone help?
Upvotes: 0
Views: 127
Reputation: 388316
You need to
menos
as a class because it is repeated in every rowit should be
$('#mais').on('click', function () {
var next = $('#lista tbody').children('tr').length + 1;
$(':input[name="qtd_itens"]').val(next);
$('#lista tbody').append('<tr>' +
'<td><input type="text" name="qtd' + next + '" size="5" /></td>' +
'<td><input type="text" name="unidade' + next + '" size="6" /></td>' +
'<td><input type="text" name="mercadoria' + next + '" size="20" /></td>' +
'<td><input type="text" name="codigo' + next + '" size="15" /></td>' +
'<td><input type="text" name="preco' + next + '" size="10" class="money" /></td>' +
'<td><input type="text" name="total' + next + '" size="10" readonly /></td>' +
'<th><a href="#" class="menos"><img src="imgs/delete.png" height="20px" width="20px"></a></th>' +
'</tr>');
return false;
});
$('#lista').on('click', '.menos', function () {
$(this).closest('tr').remove();
$(':input[name="qtd_itens"]').val(function (i, val) {
val = +val;
return val > 1 ? val - 1 : 0;
});
});
Demo: Fiddle
Upvotes: 1
Reputation: 1397
Here's a working JSFiddle. The only main problem was the way you did the subtraction $(':input[name="qtd_itens"]').val() -= 1;
.
Upvotes: 0
Reputation: 267
Instead of Id 'menos', you need to apply it as class name like,
<th><a href="#" class="menos"><img src="imgs/delete.png" height="20px" width="20px"></a></th>
Then try,
$(document).on('click','.menos', function(){
$('#lista tbody').children('tr:last').remove();
$(':input[name="qtd_itens"]').val() -= 1;
});
Upvotes: 0