开发者

Copy table row and increment all name attributes

开发者 https://www.devze.com 2023-02-24 19:46 出处:网络
Let\'s have a table like this: <table> <tr> <td><input type=\"text\" name=\"FirstName1\" /></td>

Let's have a table like this:

<table>
 <tr>
  <td><input type="text" name="FirstName1" /></td>
  <td><input type="text" name="LastName1" /></td>
 </tr>
 <tr>
  <td><input type="text" name="FirstName2" /></td>
  <td><input type="text" name="LastName2" /></td>
 </tr>
</table>

I want to have a button that will add new row at the end of the table with incremented name attributes so it will look like this:

<table>
 <tr>
  <td><input type="text" name="FirstName1" /></td>
  <td><input type="text" name="LastName1" /></td>
 </tr>
 <tr>
  <td><input type="text" name="FirstName2" /></td>
  <td><input type="text" name="LastName2" /></td>
 </tr>
 <tr>
  <td><input type="text" name="FirstName3" /></td>
  <td><input type="text" name="LastName3" /></td>
 </tr>
</table>

And so on.

So far I have this but it does not increment name attributes:

$("#newRowButton").click(function(){
  $("table tr:last").开发者_Python百科clone().appendTo("table");
});


$("#newRowButton").click(function() {
  $("table tr:last")
      .clone()
      .appendTo("table")
      .find(':input')
      .attr('name', function(index, name) {
          return name.replace(/(\d+)$/, function(fullMatch, n) {
              return Number(n) + 1;
          });
      })
});

Live demo.


$("#newRowButton").click(function(){
   var trows = $("table tr:last").clone();
   trows.find('td input').attr("name",function(i,a){
   var p = new RegExp("((?:[a-z][a-z]+))(\\d+)",["i"]);
   var m = p.exec(a);
   var index = parseInt(m[1]);
   index++;
   return m[0]+index;
   });
   trows.appendTo("table");
});


var clonedRow = $("#EventType tr:last").clone();
$("input", clonedRow).attr('name', 'FirstName3'); // reset the name

you can get the name attribute and increment by 1

Reference

0

精彩评论

暂无评论...
验证码 换一张
取 消