jQuery add form input and change input name
Solution 1
You just set the name
property of the cloned element. (Using Looks like prop
on jQuery 1.6 or above; attr
on 1.5.2 and below.attr
works on both 1.5 and 1.6; prop
also works on 1.6 and above.)
But note that the way HTML forms work, it's fine to have multiple fields with the same name, they are all sent to the server, where your code can process all of them (usually the server-side technology you're using sets them up as an array or list).
Example:
HTML:
<form id='theForm'>
<input type='text' name='picture-1'>
<input type='button' id='btnMore' value='+'>
</form>
JavaScript using jQuery:
$('#btnMore').click(function() {
var form, fields, newField;
form = $("#theForm");
fields = form.find("input[name^='picture-']");
newField = $(fields[0]).clone();
newField.attr('name', 'picture-' + (fields.length + 1));
newField.insertAfter(fields.last());
});
Solution 2
$('input[name^="picture-"]',pointertoform).length
...will give you the number of actually present input's with a name starting with "picture-", you may use this number to create the new name.
But I would prefer the solution of diEcho's comment.
eagleworks
Updated on June 04, 2022Comments
-
eagleworks almost 2 years
I'm constructing a order form for a wedding photographer, so guests can order pictures from within the client album section of his site.
Guests order between 1 and 50 pictures, so I'm currently using jQuery's
clone()
function, which is working great.However I also need to change the name attr of each input, each time I add one so the form processing can pick up on the new inputs.
name="picture-1" add field name="picture-2"
Does anyone know if this is possible?
I believe I can use
addClass()
each timeclone()
is called, but how can I makeaddClass()
to count?Thank you
-
eagleworks almost 13 yearsThank you T.J. Crowder, I didn't even think about using attr.