Reputation: 9738
I want to add table rows
as the user clicks the Add button
. In a new row there are 3 textboxes. As the rows gets added id
of textboxes should be set like array list
.
For e.g
if it is 2nd row added, the textbox ids
will be textbox1_1
textbox2_1
textbox3_1
if it is 3rd row added, the textbox ids
will be textbox1_2
textbox2_2
textbox3_2
Because I want to Add all these textboxes
values in a single string
at the end.
Added later :- Indeed at the first time there are no rows in the table.
Upvotes: 0
Views: 1753
Reputation: 1438
try this:
$("#btnAdd").click(function(){
var id = $('table tr').size(),
i,
row = '<tr>';
for(i = 1; i <= 3; i++) {
row += '<td><input type="text" id="text'+i+'_'+id+'" />';
}
row += '</tr>';
$('table').append(row);
});
DEMO Alternativly if you want to build from previous rows you can do this:
$("#btnAdd").click(function(){
var id = $('table tr').size(),
tr = $('table tr').last().clone();
$(tr).find('td').each(function (index) {
$(this).attr('id', 'text'+index+'_'+id);
});
$('table').append(tr);
});
Upvotes: 2
Reputation: 1392
write less do more with jquery. use chaining as below
$("#btnAdd").click(function(){
$('table')
.find("tr:first") // traverse the first tr
.clone() // clone the row
.appendTo('table') // append the the table tag
.end() // reset to default selector
.find('input').each(function(i,x){
$(this).prop('id',this.id.split('_')[0]+'_'+(+$('table tr').length-1)); // assign the id to the added new row
});
});
EDIT done with FIDDLE too Hope it helps....
Upvotes: 0
Reputation: 1960
Try thus
$("#btnAdd").click(function(){
var rowCount = $("table tr").length;
var firstRow = $("table tr:first").clone();
firstRow.find("input").each(function(){
this.id=this.id.replace("_0","_"+rowCount);
});
$("table").append(firstRow);
});
Upvotes: 0
Reputation: 28513
Try this : you can add row by cloning first row and updating each input
's id by iterating them.
//get the count of available row in table
var count = $('#dynamicTable tr').length;
$("#btnAdd").click(function(){
//clone the first row in table
var $tr = $('#dynamicTable tr:first').clone();
//iterate each input to change its id
$tr.find('input').each(function(){
var id = $(this).attr('id');
id = id.substring(0,id.length-1);
$(this).attr('id',id+count);
});
// update count
count++;
//add row to the table
$('#dynamicTable').append($tr);
});
Upvotes: 1