简体   繁体   中英

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.

I have a div that looks like this:

<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):

<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:

$(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.
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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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