2

I have something like this:

<div id='cb1'>
<input name='c1' value='12'>
<input name='c1' value='32'>
   ...
<input name='c1' value='32'>
</div>

<div id='z1'>
</div>

and I need to copy all the inputs from #cb1 to #z1 and rename them to x1, so I would get this:

<div id='z1'>
<input name='x1' value='12'>
<input name='x1' value='32'>
   ...
<input name='x1' value='32'>
</div>
2
  • why do you want to name all your inputs the same?! Commented Feb 1, 2011 at 13:03
  • @fearofawhackplanet it's an array Commented Feb 1, 2011 at 13:05

3 Answers 3

3
$("#cb1").children().attr("name", "x1").appendTo($("#z1"));

or

$("#cb1").children().clone(true).attr("name", "x1").appendTo($("#z1"));

Here we take the children (the inputs) from #cb1 and we optionally clone them depending on whether you want to move them from #cb1 to #z1 or whether you want to duplicate them in #z1

Then we set the attr of name to x1 for all of them and then we appendTo the #z1 container.

Argueably you want to use .find("input") as @Box9 mentioned depending on whether it has any other children. If #cb1 only has inputs then .children is faster otherwise we can take the input elements only. You can also use .children("input")

Also .find looks for nested inputs and .children only looks down one layer

.children, .attr, .appendTo, .clone, .find

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

Comments

2
$('#cb1').find('input').clone().attr('name', 'x1').appendTo('#z1');

Use .clone(true) if you have attached data and events that need to be copied too.

Comments

-1

$("#cb1").html("put here the html");

1 Comment

-1 for not knowing nor searching enough about jQuery capabilities for this kind of problem, and giving a rather bad solution. Box9 and Raynos has proven that much better solutions are available.

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.