Add and Remove HTML elements dynamically with Javascript

August 19, 2010 | In: javascript

Today I have work in magento and work was save multiple dates in an attribute witout entering multiple values in one field. and need to provide multiple text box ( with date icon to select date )where user can select date and submit the form. On the submit time I have to fill all text boxes value in a single attribute.
And this was good news for me that I have written code for this. Here I am providing basic code to create multiple text fields (elements) by javascript.
Insert below code in the head tag:

<script type="text/javascript">
var idno = 2; // It start from id 2 
function addNewElement()
{
	// mainDiv is a variable to store the object of main area Div.
	var mainDiv = document.getElementById('more_element_area');
	// Create a new div 
	var innerDiv = document.createElement('div');
	// Set the attribute for created new div like here I am assigning Id attribure. 
	innerDiv.setAttribute('id', 'divId' + idno);
	// Create text node to insert in the created Div
	var generatedContent = '<input type="text" name="new_element' + idno + '"	id="new_element' + idno + '" value="This is my text box ' + idno + '" />&nbsp;<a href="javascript:void(0)" onclick="return removeThisElement(' + idno + ')">Remove This</a>';
	// Inserting content to created Div by innerHtml
	innerDiv.innerHTML = generatedContent;
	// Appending this complete div to main div area.
	mainDiv.appendChild(innerDiv);
	// increment the id number by 1.
	idno++;
}
function removeThisElement(idnum)
{
	// mainDiv is a variable to store the object of main area Div.
	var mainDiv = document.getElementById('more_element_area');
	// get the div object with get Id to remove from main div area.
	var innerDiv = document.getElementById('divId' + idnum);
	// Removing element from main div area.
	mainDiv.removeChild(innerDiv);
 
}
</script>

Now, Put below code inside the body tag and save file and run on browser.

<div id="more_element_area">
  <div>
    <input type="text" name="new_element1" id="new_element1" value="This is my text box 1" />
  </div>
</div>
<a href="javascript:void(0)" onclick="return addNewElement()">+ Add more text box</a>