0

For example, I have such HTML:

<input name="someinput[]">

I made a function to clone/remove this input but now I want to assign indexes to name dynamically - when I make an element clones, its new names should be someinput[1], someinput[2] etc. - how to make this?

2 Answers 2

2

You could just replace [] with [index] using the attr callback:

var i = 0;
$('button').click(function(){
 $('input:first').clone().attr('name',function(a,e){    
    i++;
    return e.replace("[]","["+i+"]");
 }).insertAfter($('input:last'));
});

example: http://jsfiddle.net/niklasvh/c9G7c/

2

Keep the index of the next input in a global variable, and then use that in your cloning function. Is that what you do?

var source = $('#source')
var copy = source.clone().attr('name', 'some[' + index + ']')
$('body').append(copy);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.