Limit number of dynamically added Table Rows using JQuery
I am dynamically inserting a row into a table with JQuery using clone.
$('#Clone').cl开发者_开发知识库ick(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.
How about a variable?
function addClick(identifier, max){
var i = 0;
$(identifier).click(function() {
if (i < max){
//add row
i++;
}
}
}
addClick("#Clone", 5);
Alternatively, you could also set a different class on the user-added ones and then just count them inside your add function.
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('tr').clone(true).insertAfter($btn);
$btn.closest('table').data('theCount', currentCount + 1);
}
});
http://api.jquery.com/data/
You could just count the number of elements returned.
function countRows() {
return $("#table-id tr").length + $("#table2-id tr").length; // etc, for all table ID's.
}
Or, you could add a special class to the user-added rows.
function countRows() {
return $("tr.new").length;
}
You could also use the data attribute on the table
var i = $('#tableID').data('userAddedRows');//of course you need to check there is a value and such
i++;
$('#tableID').data('userAddedRows',i);
Then just check to make sure the i is less than the amount allowed
Thanks for your assistance but I found a JQuery Plugin that does the trick. It is here...
http://cloudgen.w0ng.hk/jquery/table.addrow.php
精彩评论