Wednesday, July 09, 2008

Dynamically Adding and Removing Text Boxes using JavaScript

After many days I was just trying to work with PHP, MySQL and JavaScript yesterday. In one of the page I wanted to add/remove text boxes on demand (or say dynamically) so after much thought and search i found the solution in using JavaScript. Here is the sample of code which I used for my purpose and may also be beneficial for you web developers who wanted to add or remove text boxes dynamically.

It simply uses two functions:
addElement(): It first gets the element id where we want to include a new element followed by creation of new element and appending it inside the element.
removeElement(): It removes the last added new element.

<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>
<p><a href="javascript:addElement();" >Add</a> <a href="javascript:removeElement();" >Remove</a></p>
<div id="content"></div>
</body>
</html>


Just drop me a comment if you have any suggestion, comments or query.