superUntitled
superUntitled

Reputation: 22527

Increment multidimensional array when form fields are cloned

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.

Upvotes: 6

Views: 3060

Answers (2)

Gabriele Petrioli
Gabriele Petrioli

Reputation: 196026

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

Upvotes: 6

sje397
sje397

Reputation: 41822

Have a look at this one: http://jsfiddle.net/sje397/z3SSL/1/

The main change is this:

var emptyQ = $("li.question").clone(),
    emptyA = $("li.answer").clone();

emptyQ.html(emptyQ.html()
               .replace("question[" + (nextId - 1), "question[" + nextId)
               .replace("qnotes[" + (nextId - 1), "qnotes[" + nextId));
emptyA.html(emptyA.html()
               .replace("answer[" + (nextId - 1), "answer[" + nextId)
               .replace("anotes[" + (nextId - 1), "anotes[" + nextId));

Upvotes: 1

Related Questions