Dynamically add and remove html elements

by Nirmala 2009-06-08 13:25:01

Hi...
Use the below code to create html elements dynamically.

<html>
<head>
<title>Adding and Removing Text Boxes Dynamically</title>
<script type="text/javascript">
var intTextBox=0;

//FUNCTION TO ADD TEXT BOX ELEMENT
function addElement()
{
intTextBox = intTextBox + 1;
var contentID = document.getElementById("content");
var newTBDiv = document.createElement("div");
newTBDiv.setAttribute("id","strText"+intTextBox);
newTBDiv.innerHTML = "Text"+intTextBox+": <input type='text' id='" + intTextBox + "' name='" + intTextBox + "'>";
contentID.appendChild(newTBDiv);
}

//FUNCTION TO REMOVE TEXT BOX ELEMENT
function removeElement()
{
if(intTextBox != 0)
{
var contentID = document.getElementById("content");
contentID.removeChild(document.getElementById("strText"+intTextBox));
intTextBox = intTextBox-1;
}
}
</script>
</head>
<body>
<p>Demo of Adding and Removing Text Box Dynamically using JavaScript</p>
<input type="button" onclick="addElement()" value="Add"> <br><input type="button" onclick="removeElement()" value="Remove"></p>
<div id="content" ></div>
</body>
</html>

Tagged in:

9190
like
3
dislike
0
mail
flag

You must LOGIN to add comments