Pues seria esto:
Código Javascript
:
Ver original$(document).ready(function ($) {
// trigger event when button is clicked
$("button.add").click(function () {
// add new row to table using addTableRow function
addTableRow($("table"));
// prevent button redirecting to new page
return false;
});
function cambiar_nombre_id(){
//he puesto 300 milisegundos de retraso para estar seguro que la nueva fila esta en el DOM
setTimeout(function(){
//cuento todas las filas
$.each($(table).find("tbody tr"),function(index){
// get the name attribute for the input and select fields
$(this).find("input,select").attr("name", function () {
// break the field name and it's number into two parts
var parts = this.id.match(/(\D+)(\d+)$/);
// create a unique name for the new field by incrementing
// the number for the previous field by 1
//aqui solo empleo la primera parte que es el nombre
//en vez de la segunda parte he puesto el index actual incrementando una unidad ya que empieza por 0
return parts[1] + (index+1);
// repeat for id attributes
}).attr("id", function () {
var parts = this.id.match(/(\D+)(\d+)$/);
return parts[1] + (index+1);
});
});
},300);
}
// function to add a new row to a table by cloning the last row and
// incrementing the name and id values by 1 to make them unique
function addTableRow(table) {
// clone the last row in the table
var $tr = $(table).find("tbody tr:last").clone();
//llamo a la funcion para cambiar nombres e id-s despues de añadir nueva fila
cambiar_nombre_id();
// append the new row to the table
$(table).find("tbody tr:last").after($tr);
$tr.hide().fadeIn('slow');
// row count
rowCount = 0;
$("#table tr td:first-child").text(function () {
return ++rowCount;
});
// remove rows
$(".remove_button").on("click", function () {
if ( $('#table tbody tr').length == 1) return;
$(this).parents("tr").fadeOut('slow', function () {
$(this).remove();
//llamo a la funcion para cambiar nombres e id-s despues de borrar una fila
cambiar_nombre_id();
rowCount = 0;
$("#table tr td:first-child").text(function () {
return ++rowCount;
});
});
});
};
});
Ahora ya esta probado ... como ya he dicho ... es algo rudimentario ... seguro habran formas mas elegantes de hacerlo pero funciona.