I have a form that allows for a set of form fields to be duplicated (see here: http://jsfiddle.net/Sd9Ag/8/ ). How would I increment the array number in the name attribute when the inputs are duplicated.
For example:
<input type="input" name="question[1]" />
<input type="input" name="questionURL[1]" />
<input type="input" name="answer[1][]" />
<input type="input" name="answerURL[1][]" />
And when it is cloned, increment the array number:
<input type="input" name="question[2]" />
<input type="input" name="questionURL[2]" />
<input type="input" name="answer[2][]" />
<input type="input" name="answerURL[2][]" />
The reason I need to do this is so that the questions and answers are grouped when the form is submitted.
update
Ok, i have used your jsfiddle (which i missed in my first answer) code and made some alterations.
qnote[1]
to avoid confusion with answer notesanswer[1][1]
for first answer to first question, answer[1][2]
for second answer to first question ... answer[2][1]
for first answer of second question, etc..working code at http://jsfiddle.net/dcUdU/1/
original answer
Use the following code
elem.name = elem.name.replace(/\[(\d+)\]/,function(str,p1){
return '[' + (parseInt(p1,10)+1) + ']';
});
for each
of the input elements you have cloned (you need to clone
from the last group of fields)
It uses a regular expression to find the number inside the [
and ]
and increment it by one.
example at http://www.jsfiddle.net/gaby/WZAU6/
reference for function as parameter to the replace method
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With