Dynamically Adding and Removing Text Boxes using JavaScript

In one of the webpage I wanted to add and remove input text boxes on demand (or say dynamically) so after much thought and search I found the solution in using pure JavaScript. Here is the sample of code which I used for this purpose and may also be beneficial for you web developers who wanted to add or remove text boxes dynamically using only JavaScript.

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 with unique id.
removeElement(): It removes the last added new element.

Here is well documented simple code for quick reference:

<!DOCTYPE html>
<html>
<head>
<meta charset=”utf-8″ />
<title>Dynamically adding and removing textboxes</title>
<script type=”text/javascript”>
//Counter to maintain number of textboxes and give them unique id for later reference
var intTextBox = 0;

/**
* Function to add textbox element dynamically
* First we incrementing the counter and creating new div element with unique id
* Then adding new textbox element to this div and finally appending this div to main content.
*/
function addElement() {
intTextBox++;
var objNewDiv = document.createElement(‘div’);
objNewDiv.setAttribute(‘id’, ‘div_’ + intTextBox);
objNewDiv.innerHTML = ‘Textbox ‘ + intTextBox + ‘: <input type=”text” id=”tb_’ + intTextBox + ‘” name=”tb_’ + intTextBox + ‘”/>’;
document.getElementById(‘content’).appendChild(objNewDiv);
}

/**
* Function to remove textbox element dynamically
* check if counter is more than zero then remove the div element with the counter id and reduce the counter
* if counter is zero then show alert as no existing textboxes are there
*/
function removeElement() {
if(0 < intTextBox) {
document.getElementById(‘content’).removeChild(document.getElementById(‘div_’ + intTextBox));
intTextBox–;
} else {
alert(“No textbox to remove”);
}
}
</script>
</head>
<body>
<p>Demo of adding and removing textboxes dynamically using simple JavaScript</p>
<p>
<a href=”javascript:void(0);” onclick=”addElement();”>Add</a>
<a href=”javascript:void(0);” onclick=”removeElement();”>Remove</a>
</p>
<div id=”content”></div>
</body>
</html>

You can also play with this code here: http://jsfiddle.net/ursdeep/76hxapd9/

Let me know if it is any helpful for you or if you have any query and also suggestions to improve the same.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s