Duplicating DIVs and nested elements

Hi Experts,

When the user cclicks on a button, using jQuery, how can I duplicate an entire DIV with its elements?

For some elements, at design time I want to have
<input type="file" id="fie[0]" name="file[0]">

Open in new window

...and when duplicating, I would need the [index++] updated, so that it would be an nested array in my $_POST

Thank you
APD TorontoAsked:
Who is Participating?
Julian HansenCommented:
First question - do you need the input id and if so what for?
Second question - why even use indexes for the name just do this
<input type="file" name="file[]">

Open in new window

This will result in an array of files being submitted to the server which PHP will understand and return as an array for you.

Then you can just clone the div on a button click
  <form action="reflect.php" method="post" enctype="multipart/form-data">
    <div class="div-container">
      <div id="div-to-clone">
        <p>Some content to make this look intersting</p>
        <input type="file" name="file[]">
    <button id="add-div" class="btn btn-success">Add</button>
    <button type="submit" class="btn btn-primary">Submit</button>

Open in new window

$(function() {
  $('#add-div').click(function(e) {

Open in new window

Working sample here
Just use : <input type="file" name="file[]">
so you can read every file using $_FILE with PHP, check this comment :

else, the following change the name attribute. use same logic for ID attribute if you really need it... Only the name is used to POST data to the server....
jQuery(function($) {
      $("#your_button").click(function(evt) {
            evt.preventDefault(); // prevent any submitting of the form/page
            var clone = $("#divToDuplicate").clone();
            index++; // somewhere, I'm assuming you set index a zero or something else...
            $("[name]", clone).each(function() { // for each element inside the clone with a name attribute
                 var previousName = $(this).attr("name");
                 var newName = previousName.replace(/\[\d*\]/g, "[" + index + "]");
                 $(this).attr("name", newName);

Open in new window

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.