Umer bin Siddique Umer bin Siddique - 2 years ago 90
jQuery Question

Dynamically add tables and dynamically add rows in them using jQuery

here i am facing the problem when dynamically adding tables and add rows in them dynamically as well. here what i tried: https://jsfiddle.net/753ynxn3/`

$(document).on('click', "#add_row" + j, function() {
$(this).siblings('.appendHere').children('table').children('tbody').children('#addr' + j).html("<td>" + (j + 1) + "</td><td><input type='text' name='attribute0' placeholder='Attribute' class='form-control'/></td><td><input type='text' name='productId0' placeholder='Product Id' class='form-control'/></td>");
$(this).siblings('.appendHere').children('table').children('tbody').append('<tr id="addr' + (j + 1) + '"></tr>');
j++;
});


its working for with adding tables when i add 3rd table and click on add row in this table that is stuck.

Answer Source

the problem is, when you click every time on add row button the value of j is incrementing and changing, on other hand when you click on add table the value of j is not reset for new table. we need to reset the value of variable j. here is your updated fiddle: https://jsfiddle.net/j2mkL0qp/

i have done this main update:

 j = parseInt($(this).siblings('.appendHere').children('table').children('tbody').children('tr:nth-last-child(2)').children('td:first-child').text())
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download