Adding elements dynamically with JavaScript

In today's post we will create a program where user can add multiple items either form elements, images, div or any thing dynamically with JavaScript. This can be useful where you want to add multiple user's data, want to create questionnaire or multiple tasks items. We will only discuss adding elements and deleting them with JavaScript but it can be embedded with PHP and SQL queries to store data in Database.

First of all create the HTML file where we will add the our HTML markup which can be form, div or images.
+ Add New Item

we have created a form where we want to add user name and email. Put this fields inside a div with class name field. After that create another div with id name newLayer, in this div we will add our elements dynamically. At the end add an anchor tag where we will call our function 'AddNewItem()' with onclick JavaScript.

Now we will create our function AddNewItem() to add elements
var itemID = 100;
function AddNewItem() {
	var html='
'; html=''; html='Delete
'; var newDiv; newDiv = document.createElement("DIV"); newDiv.innerHTML=html;"field"+itemID; document.getElementById('newLayer').insertBefore(newDiv, null); itemID++; }
Here first we initialized a variable itemID with the value of 100, you can change it according to your requirements. After that we created variable html where we inserted all the elements we want to add dynamically. Remember the most important thing is not to add any space between elements tag's which will cause an error in JavaScript. We have added itemID value in the div id's so that every time we create new elements we get new id.

After that create new variable newDiv in which we will create a div element dynamically with createElement JavaScript, put your html in this div and give it a id with itemID value to create unique id. At the end put this div with its content inside newLayer div which we created in our HTML markup and increase value of itemID.

You will notice that with every new layer we are adding anchor with text delete which is calling function deleteItem(). This will help us to delete the layer which we want to delete.
function deleteItem(ID) {
	document.getElementById("field"+ID).innerHTML = '';
	document.getElementById("field"+ID).style.display = 'none';
This was all we needed to create a simple templete to add dynamic elements.You can create purchase orders, student forms, Questionnaire and many other things with few additions. You can view live demo from following link.

View Demo
Tags: JavaScript
comments powered by Disqus