Vamos ter uma tabela assim:
Eu quero ter um botão que irá adicionar nova linha no final da tabela com atributos de nome incrementados para que fique assim:
E assim por diante.
Até agora eu tenho isso, mas não incrementa atributos de nome:
$("#newRowButton").click(function(){ $("table tr:last").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; }); }) });
Demonstração ao vivo .
$("#newRowButton").click(function(){ var trows = $("table tr:last").clone(); trows.find('td input').attr("name",function(i,a){ var p = new RegExp("((?:[az][az]+))(\\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
você pode obter o atributo name e incrementar em 1
Referência