Clone HTML using jQuery

by Vincy. Last modified on July 12th, 2022.

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

Leave a Reply

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

↑ Back to Top

Share this page