克隆表单字段时增加多维数组 [英] Increment multidimensional array when form fields are cloned

查看:80
本文介绍了克隆表单字段时增加多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个允许复制一组表单字段的表单(请参见此处: http://jsfiddle.net/Sd9Ag/8/).输入重复时,如何增加name属性中的数组编号.

例如:

<input type="input" name="question[1]"  />
<input type="input" name="questionURL[1]"  />
<input type="input" name="answer[1][]"  />
<input type="input" name="answerURL[1][]"  /> 

克隆后,增加数组编号:

<input type="input" name="question[2]"  />
<input type="input" name="questionURL[2]"  />
<input type="input" name="answer[2][]"  />
<input type="input" name="answerURL[2][]"  />

我需要这样做的原因是,以便在提交表单时将问题和答案分组.

解决方案

更新

好吧,我已经使用了您的jsfiddle(我在第一个答案中遗漏的 )代码并进行了一些改动.

  • 我将问题的笔记重命名为qnote[1],以避免与答案笔记混淆
  • 第一个问题的第一个答案的答案为answer[1][1],第一个问题的第二个答案的名称为answer[1][2]第二个问题的第一个答案的名称为answer[2][1],等等.
位于 http://jsfiddle.net/dcUdU/1/

上的工作代码

原始答案

使用以下代码

   elem.name = elem.name.replace(/\[(\d+)\]/,function(str,p1){
         return '[' + (parseInt(p1,10)+1) + ']';
       });

对于已克隆的输入元素的 each (,您需要<最后一组字段中的href ="http://api.jquery.com/clone/" rel ="noreferrer"> clone )

它使用正则表达式在[]中查找数字并将其递增1.

示例 http://www .jsfiddle.net/gaby/WZAU6/

作为替换方法参数的参数的参考

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.

  • 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

这篇关于克隆表单字段时增加多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆