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.

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

function addElement()
intTextBox = intTextBox + 1;
var contentID = document.getElementById('content');
var newTBDiv = document.createElement('div');
newTBDiv.innerHTML = "Text "+intTextBox+": <input type='text' id='" + intTextBox + "' name='" + intTextBox + "'/>";

function removeElement()
if(intTextBox != 0)
var contentID = document.getElementById('content');
intTextBox = intTextBox-1;
<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>

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


Munna said...

Hi Deeps... It's a good work. Thanks. But i'm facing a problem. When i submit the form i'm unable to read the values which has been entered using php. Plz suggest me something..
you can PM me on

Heru said...

Hi Deeps, how if I wanna do 2 textboxes side by side and adding a pair of textboxes everytime I need them. For example, left textbox is for the name and right textbox is for this person salary?

I tried to modify your code and it did not work

Thanks Deeps!

Ashish said...

Thanks Deep !!

Congrates for your great work !!

navaro said...

hey, great code, but it wont work for me in WP 2.9 :( Dont you have an idea why? (quotes are fine)

pragal said...

hai deep,

Thanks for Your code, it really help form me. can u do it with more text boxes with a click.


pragal said...

hi deep,

can u do this to create multiple text boxes with a single click, Your code really helps me.