jQuery clone div with unique attributes (+ examples)
Hey guys, sometimes we need to clone html elements like div with jquery but also want to assign unique attributes to them.
So, I am here with a jquery tutorial and we are going to solve this together.
Live Demo
We have created a live demo on codepen for you. You can check unique attributes by inspect element of new added div.
Local setup of project
Because we have used php form submission in this tutorial, So, let’s set up our code on localhost.
Go to your localhost directory like htdocs or www. Then open your command terminal and run the following command
git clone https://github.com/SATPAL-BHARDWAJ/clone-div-jquery.git
It will clone the clone-div-jquery project to your local server. And now open your web browser and type following url
localhost/path-to/clone-div-jquery
Replace “path-to” with your actual directory, if you have any otherwise if you clone this project to the root like htdocs or www directly then use only “/clone-div-jquery”.
Let’s go through the complete code one by one.
Create the html page
Let’s assume we have html page something like below,
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery clone an element and assign unique attributes</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.2/css/bootstrap.min.css" integrity="sha512-usVBAd66/NpVNfBge19gws2j6JZinnca12rAe2l+d+QkLU9fiG02O1X8Q6hepIpr/EYKZvKx/I9WsnujJuOmBA==" crossorigin="anonymous" referrerpolicy="no-referrer" /> <link rel="stylesheet" href="assets/css/font-awesome-4.7.0/css/font-awesome.min.css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.2/js/bootstrap.min.js" integrity="sha512-a6ctI6w1kg3J4dSjknHj3aWLEbjitAXAjLDRUxo2wyYmDFRcz2RJuQr5M3Kt8O/TtUSp8n2rAyaXYy1sjoKmrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> </head> <body> <div class="container"> <form class="form-floating mt-5" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]) ?>"> <div class="border p-3 d-flex justify-content-end"> <button type="button" class="btn btn-secondary m-2 add-new-js"> Add New </button> <button type="submit" class="btn btn-primary m-2"> Save </button> </div> <div class="group border p-3 section-group-js" data-index="0"> <div class="d-flex justify-content-between align-items-center py-2 action-js"> <p class="m-0 text-black-50">Person Details : #<span class="sn-js">1</span></p> </div> <div class="form-floating mb-3"> <input type="text" name="details[0][name]" class="form-control" id="name_0" placeholder="Enter your name"> <label> Name </label> </div> <div class="form-floating mb-3"> <input type="email" name="details[0][email]" class="form-control" id="email_0" placeholder="name@example.com"> <label>Email address</label> </div> </div> </form> </div> </body> </html>
We have added some PHP code here to submit the form at the end and check our dynamically added inputs working. We can see that all inputs get the values and are successfully submitted with php.
JQuery to clone div with unique attributes
So, the following jquery is used to do jquery clone div with unique attributes. Here we have attributes like name and id for inputs and few other text changes, all will be dynamically updated with new incremented values.
$(document).on('click', '.add-new-js', function() { var form = $(this).closest('form'); var section = form.find('.section-group-js:last-child'); var index = section.data('index'); var newIndex = index + 1; var newSection = section.clone(); console.log(index, typeof index); newSection.find('input').val(''); newSection.data('index', newIndex); newSection.attr('data-index', newIndex); newSection.find('.sn-js').text(newIndex + 1); if ( newSection.find('.remove-js').length === 0 ) { newSection.find('.action-js').append(` <button type="button" class="btn btn-danger remove-js"> <i class="fa fa-trash"></i> </button> `); } updateAttributes(newSection, 'name', index); updateAttributes(newSection, 'email', index); newSection.insertAfter(section); }) $(document).on('click', '.remove-js', function() { var section = $(this).closest('.section-group-js'); section.remove(); }); function updateAttributes( newSection, key, index ) { var section = newSection.find(`[name="details[${index}][${key}]"]`); section.attr('name', `details[${index+1}][${key}]`); section.attr('id', `${key}_${index+1}`); }
When a user clicks on the “add new” button we are getting the closest form element. Then we will find the section group div but only the last child of the form.
We have already set up the data-index on this div, it will help us to determine the div index and we can increment this index for the next cloned div.
All other attributes like name, id and text changes will be updated as per this index value.
The update attributes function will help us to update required attributes with a new index and will provide us with clean and readable code.
Remove element with jquery
It will add the remove button to the cloned div, so that users can remove new elements. We have created a jquery listener for click events on the remove button. It will remove the current div element.
$(document).on('click', '.remove-js', function() { var section = $(this).closest('.section-group-js'); section.remove(); });
PHP form submission
After finishing this, we also tested the form submission with these dynamic inputs and we got the desired results. We have put this code before doctype html element and it will show the submitted values.
<?php if ( $_SERVER['REQUEST_METHOD'] === 'POST' ) { echo "<pre>"; print_r($_POST); echo "</pre>"; die; } ?>
After submitting the form the output array will be as below.
Array ( [details] => Array ( [0] => Array ( [name] => riya [email] => riya@gmail.com ) [1] => Array ( [name] => aman [email] => aman@gmail.com ) [2] => Array ( [name] => mira [email] => mira@gmail.com ) ) )
Hope you find this article useful.
See you in the next learning journey.