views:

772

answers:

2

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?

+1  A: 

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.

Rick Hochstetler
Actually that will only change the name attribute of the div referred to by this. In my example <div> your solution would create <div name="title1"> but would not change the field name attributes. I'm trying to change the name attributes of the various fields within the div, not the div itself.
gaoshan88
+2  A: 

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.

Paolo Bergantino
I think you want (\d+) for when you get to 10
cobbal
Actually I think your way of putting the fields into an array is better than what I was trying to do (I am using PHP). I guess I was thinking about it from the wrong angle. Thanks (again) Paolo.
gaoshan88