Toni Michel Caubet
Toni Michel Caubet

Reputation: 20163

Clone element and increment index placed in name by 1

Lets say I have this input:

name="fecha_inicio[2]"

And I want to clone it and generate:

name="fecha_inicio[3]"

How can I do so?

I tried something like this, but Its ugly and it won't work..

var $input = $original.clone();
var name = $input.attr('name');     
name.replace('['+(indice-1)+']', '['+indice+']');   
$input.attr('name', name);

Upvotes: 2

Views: 185

Answers (1)

dfsq
dfsq

Reputation: 193261

replace method doesn't modify string in place, but returns a new string. So your code should be:

name = name.replace('['+(indice-1)+']', '['+indice+']');   

Also maybe you don't really need to have such index names. You can simply go with name="fecha_inicio[]" and don't worry about index. Later you would get form data with say serialize method.

Upvotes: 1

Related Questions