Clone HTML using jQuery

In this tutorial, we are going to see how to copy and insert HTML element dynamically. In the previous tutorial, we have added HTML form elements dynamically by using jQuery load() function.

In this example, we are using jQuery clone() to copy HTML element. And then by using jquery insert function, we are adding an element to the target div.

View Demo

HTML Textbox to Clone

This code contains textbox input to specify product name and price. This input element is cloned for adding multiple product entries.

jquery-clone

<DIV id="product-header">
<DIV class="float-left"> </DIV>
<DIV class="float-left col-heading">Item Name</DIV>
<DIV class="float-left col-heading">Item Price</DIV>
</DIV>
<DIV id="product">
	<DIV class="product-item float-clear" style="clear:both;">
	<DIV class="float-left"><input type="checkbox" name="item_index[]" /></DIV>
	<DIV class="float-left"><input type="text" name="item_name[]" /></DIV>
	<DIV class="float-left"><input type="text" name="item_price[]" /></DIV>
	</DIV>
</DIV>
<DIV class="btn-action float-clear">
<input type="button" name="add_item" value="Add More" onClick="addMore();" />
<input type="button" name="del_item" value="Delete" onClick="deleteRow();" />
</DIV>

jQuery Clone Function

In this script, we are using jQuery clone and insert functions to add dynamic textboxes in the product form.

function addMore() {
	$(".product-item:last").clone().insertAfter(".product-item:last");	
}
function deleteRow() {
	$('DIV.product-item').each(function(index, item){
		jQuery(':checkbox', this).each(function () {
            if ($(this).is(':checked')) {
				$(item).remove();
            }
        });
	});
}

View DemoDownload

Photo of Vincy, PHP developer
Written by Vincy Last updated: July 12, 2022
I'm a PHP developer with 20+ years of experience and a Master's degree in Computer Science. I build and improve production PHP systems for eCommerce, payments, webhooks, and integrations, including legacy upgrades (PHP 5/7 to PHP 8.x).

Leave a Reply

Your email address will not be published. Required fields are marked *

Explore topics
Need PHP help?