简体   繁体   English

创建动态表单元素(具有递增的名称属性)

[英]creating dynamic form elements (with incremented name attributes)

How can I dynamically create a form element and provide it with dynamically incremented input name attributes? 如何动态创建表单元素并为其提供动态增加的输入名称属性? I'm working with jquery but am open to any solutions. 我正在使用jquery,但我愿意接受任何解决方案。

I have a div that looks like this: 我有一个看起来像这样的div:

<div>

<input type="text" name="title1" />

<input type="text" name="body1" />

<select name="photo1" size="1">

<option value="0">foo</option>

</select>

</div>

and I want to clone it n times AND increment the name values by 1 so, for example, a second div would look like this (only the name values change): 我想克隆它n次并将名称值增加1,所以,例如,第二个div看起来像这样(只有名称值改变):

<div>

<input type="text" name="title2" />

<input type="text" name="body2" />

<select name="photo2" size="1">

<option value="0">foo</option>

</select>

</div>

Cloning a div is simple with jquery: 使用jquery克隆div很简单:

$(document).ready(function(){
    $('.toClone').click(function(){
        $(this).clone(true).insertAfter(this);
     });
});

but I am having trouble automatically incrementing the name value of the dynamically created div fields. 但我无法自动增加动态创建的div字段的名称值。
Anyone have insight into how to do this? 任何人都有洞察力如何做到这一点?

What are you processing this with? 你用什么处理这个? With PHP you can name the fields title[] , body[] , etc. so they get sent as an array. 使用PHP,您可以将字段命名为title[]body[]等,以便将它们作为数组发送。 This would be the best way to do it, as cloning would then be trivial. 这将是最好的方法,因为克隆将是微不足道的。 It works similarly for other technologies, as far as I know. 据我所知,它的工作方式与其他技术类似。 Anyhow, if you really want to do it your way: 无论如何,如果你真的想按照自己的方式去做:

$(document).ready(function(){
    $('.toClone').click(function(){
        var el = $(this).clone(true).insertAfter(this);
        var regex = new RegExp(/^(.+)(\d+)$/);
        $(el).find(':input').each(function() {
            var match = $(this).attr('name').match(regex);
            $(this).attr('name', match[1] + (++match[2]));
        });
    });
});

That should do the trick. 这应该够了吧。

Changing the name attribute field can be done with the following: 可以使用以下命令更改名称属性字段:

var i = 1;
$(this).clone(true).attr('name', 'title' + i).insertAfter(this);

Then you just need to manage incrementing the variable. 然后你只需要管理递增变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM