Link to home
Start Free TrialLog in
Avatar of APD Toronto
APD TorontoFlag for Canada

asked on

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
Avatar of leakim971
leakim971
Flag of Guadeloupe image

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);
            });
            clone.appendTo(whereYouWantToPutIt);
      });
});

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial