Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Increment multidimensional array when form fields are cloned

Tags:

jquery

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.

like image 762
superUntitled Avatar asked Dec 16 '10 23:12

superUntitled


1 Answers

update

Ok, i have used your jsfiddle (which i missed in my first answer) code and made some alterations.

  • the note of the question i renamed to qnote[1] to avoid confusion with answer notes
  • answers are named as answer[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

like image 63
Gabriele Petrioli Avatar answered Oct 18 '22 21:10

Gabriele Petrioli