How to Copy Table Row with clone in jquery and create new Unique Ids for the controls

前端 未结 1 1314
情深已故
情深已故 2020-11-28 21:17

How to Copy Table Row with clone in jquery and create new Unique Ids for the controls.Clone will acually copy data also .i don\'t want data to be copied .

The table

相关标签:
1条回答
  • 2020-11-28 21:33

    You could do something like this:

    var i = 1;
    $("button").click(function() ​​​{
      $("table tr:first").clone().find("input").each(function() {
        $(this).val('').attr('id', function(_, id) { return id + i });
      }).end().appendTo("table");
      i++;
    })​;​
    

    This would empty the values for new rows and give them unique IDs starting with txtTitle1, txtTile2, etc.

    You ca give it a try here. If you needed to change the name too I'd pass an object to .attr() to keep it a bit cleaner, like this:

    var i = 1;
    $("button").click(function() {
      $("table tr:first").clone().find("input").each(function() {
        $(this).attr({
          'id': function(_, id) { return id + i },
          'name': function(_, name) { return name + i },
          'value': ''               
        });
      }).end().appendTo("table");
      i++;
    });​
    

    You can try that version out here.

    0 讨论(0)
提交回复
热议问题