Rob Rob - 8 months ago 46
jQuery Question

Limit number of dynamically added Table Rows using JQuery

I am dynamically inserting a row into a table with JQuery using clone.

$('#Clone').click(function() {

//put jquery this context into a var
var $btn = $(this).parent();

//use .closest() to navigate from the buttno to the closest row and clone it
//use clone(true) to pass events to cloned item

var $clonedRow = $btn.closest('tr').clone(true).insertAfter($btn);


The end user will control the insertion of new rows. I need to limit the number of new rows to 5. Is there a way to do this with a cookie or some other method (array). I could have multiple tables with there own unique id so it needs to work with multiple tables on the page.

Hope you can help.


You could always simply use a variable for each table to track the number of added rows.

Or another alternative would be to use jQuery's data() method which allows you to store data in a dom element directly. The click event would find its table, and update the table's data() each time a row is added, and prevent further additions when it reaches the maximum.

EDIT: Corrected code with check to see if theCount is undefined, and to remove a mis-placed parentheses.

$('#Clone').click(function() {
    var $btn = $(this).parent();
    if($btn.closest('table').data('theCount') == undefined) {
        $btn.closest('table').data('theCount', 0)
    var currentCount = $btn.closest('table').data('theCount');

    if(currentCount < 5) {
        $btn.closest('table').data('theCount', currentCount + 1);