Hello.
I'm a jQuery newbie and I'm having trouble with it.
I decided to create a new post even though there were already a couple of threads with a similar title because I tried (some) of the solutions provided in those threads and it didn't solve my problem.
I want to append a specified number of rows to an existing HTML table using jQuery. The idea is to let the user input the number of rows to add the table.
I've tried something like the following:
- $(document).ready(function() {
$('#addField').live("click",function(){
var qty = $('#qty').val();
//var rowCount = $('table#container tr:last').index() + 1;
var rowCount = $('table#container').prop('rows').length;
//for (var i=0; i<qty; i++) //from 0 to qty doesn't work because it would append the number of already existing rows plus the number inserted by the user
for (var i=rowCount; i<sum(rowCount,qty); i++)
{
$("table#container").find('tr.newField').clone().insertAfter('#container tr:last').find("input[type='text']").each(function() {
$(this).attr({
'id': function(_, id) { return id + (i) },
'name': function(_, name) { return "fieldNames[]" },
'value': ''
});
})//.end().appendTo("#container");
}
//These alert statements were just for (attempted) debugging, please disregard it
alert('rowCount = ' + $('table#container').prop('rows').length);
alert($('table#container tr:last').index() + 1);
});
var sum = function(a,b) {
return parseInt(a,10) + parseInt(b,10);
}
});
The problem is, even though it seems to work correctly if I add one row the first time, when I add more rows it starts inserting more lines than it should.
Here's the jsfiddle
link.
Thanks in advance.