Reputation: 2197
I need to add rows to a table dynamically when the command was given by the user to add them to the end of a printed rows. But the number of columns must add for a particular row vary by table to table.
The number of columns should add is getting dynamically to each table. So the printed number of columns must vary time to time. This is the code I used.
$(document).ready(function(){
$("#anc_add").click(function(){ //This is the ID of the button where user gives the command to add rows.
var Total=$("#NumberOfColumns").val(); //This is the number of input boxes I must add to that row......
$('#tbl1 tr').last().after(
'<tr><td>Static Content ['+cnt+']</td><td><input type="text" name="txtbx'+cnt+'" value="'+cnt+'">;
); // I need to print the given(Total) number of input boxes instead of printing textboxes like this.
cnt++;
});
});
Could anyone please suggest me a way to do this. Thank you so much.
Upvotes: 1
Views: 785
Reputation: 8315
A suggestion :
// What you want your new rows to be filled with :
var defaultValues = {
'col0' : 'val0',
'col1' : 'val1',
'col2' : 'val2'
};
// A "template", which could be inside the HTML, to keep the code clear, i.e
// out of loops and if possible out of JavaScript.
var rowTemplate =
'<tr>' +
'<td>{{col0}}</td>' +
'<td>{{col1}}</td>' +
'<td>{{col2}}</td>' +
'</tr>';
var oldNbRows = ...,
newNbRows = ...;
// Only select the table once, unless it is dynamically created / deleted.
var $table = $( '#myTable' );
// Add extra rows :
for( var i = 0, maxI = newNbRows - oldNbRows; i < maxI; ++i )
{
var html = rowTemplate;
for( var key in defaultValues )
{
html.replace( '{{' + key + '}}', defaultValues[key] );
}
$table.children( 'tr' ).last().after( html );
}
Upvotes: 0
Reputation: 1956
This will loop the total number of inputs you want to add.
$("#anc_add").click(function(){ //This is the ID of the button where user gives the command to add rows.
var Total=$("#NumberOfColumns").val();
var rowElem = $('<tr>').append(
$('<td>').html('Static Content ['+cnt+']')
);
for(var i = 0; i < Total; i++) {
rowElem.append(
$('<td>').html('<input type="text" name="txtbx'+cnt+'" value="'+cnt+'">')
)
cnt++;
}
$('#tbl1 tr').last().after(
rowElem
);
});
});
Upvotes: 1
Reputation: 3559
Try this:
$('#my_table > tbody > tr').eq(i-1).after(html);
or
$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');
Upvotes: 0