单击按钮时添加表行

Adding Table Rows on Button Click

本文关键字:添加 按钮 单击      更新时间:2023-09-26

我想在用户单击Add button时添加table rows。在新行中有3个文本框。当添加行时,文本框的id应设置为类似array list

例如
如果添加了第二行,则文本框ids将为textbox1_1 textbox2_1 textbox3_1
如果添加了第3行,则文本框ids将为textbox1_2 textbox2_2 textbox3_2

因为我想在最后将所有这些textboxes值添加到一个single string中。

小提琴

稍后添加:-事实上,表中第一次没有行。

试试这个:

$("#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);
});

演示或者,如果你想从前面的行构建,你可以这样做:

$("#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);
});

DEMO

试试这个:您可以通过克隆第一行来添加行,并通过迭代来更新每个input的id。

//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);
});

JSFiddle链接

这样尝试

$("#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);
});

演示

用jquery少写多做。使用以下的链接

$("#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
    });
});

编辑也使用FIDDLE完成希望有帮助。。。。