2

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 time clone() is called, but how can I make addClass() to count?

Thank you

2
  • 1
    better to use <input name="picture[]" /> if server side language is PHP Commented May 5, 2011 at 11:50
  • 1
    @diEcho: If you're using PHP on the server. Commented May 5, 2011 at 11:54

3 Answers 3

5

You just set the name property of the cloned element. (Using prop on jQuery 1.6 or above; attr on 1.5.2 and below. Looks like 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());
});

Live copy

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you T.J. Crowder, I didn't even think about using attr.
1
$('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.

Comments

0

try this ( raw code)

$(some_cloned_element).each(function(i, elem){
    var newName = "yay_i_love_my_new_name";
    if ($.browser.msie === true){ // evil browser sniffing *cries*
        $(elem).replaceWith(document.createElement(
            this.outerHTML.replace(/name=\w+/ig, 'name='+newName+'_'+i)
        ));
    } else {
        $(elem).attr('name',newName+'_'+i);
    }
    $("body").append(some_cloned_element);
});

check when i=50 and then break/exit

better way : use name as array like name=picture[]

Refernece

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.