Tuesday, May 12, 2009

Dynamically adding text box in web page using javascript.


Some times we need to add text box dynamically in a web page.

For example, assume that our web page is having option to add email id of many friends.

It is very difficult to judge how many friends will be there for each person.
So we can provide few text boxes (e.g 3) for entering email id when loading the page and we need to provide a button for adding more text boxes if required.

Javascript can be used for adding more text boxes without doing page refresh.

Find below an example. If you click "Add Inputbox" button a new input box will be added.














The code used for doing above example is as below

The below HTML code should added within body tag of HTML page.



<form name="" action="" method="post">
<table border="0" width="100%">
<tbody id="inputtable">
<tr><td><input type="text" name="inputbox[]" /></td></tr>
</tbody>
</table>

<table border="0" width="100%">
<tr>
<td><input type="button" value="Add Inputbox" onclick="addRow();" /></td>
</tr>

</table>
</form>




onclick event of "Add Inputbox" button is calling a javascript function addRow().

This function should be added within head tag of HTML page as below.


function addRow()
{
tabBody=document.getElementById("inputtable");
row=document.createElement("TR");
cell1 = document.createElement("TD");
textnode1=document.createElement("input");
textnode1.name="inputbox[]";
textnode1.type="text";

cell1.appendChild(textnode1);
row.appendChild(cell1);
tabBody.appendChild(row);

}




On calling this addRow function, an object called "tabBody" is created using getElementById method of document object for representing the table to which we need to add new text boxes.

createElement method of document object is used for creating an object "row" for representing table row (i-e "TR" tag).

Similarly, textnode1 and cell1 objects are created using createElement method.

appendChild method is used for inserting these newly created objects in appropriate hierarchy to table.


More Articles...

1 comment:

priyam88 said...

How I will bw able to fetch the values from the textboxes later if I want to?? they must conatain an unique id or name.Please show the code.

Search This Blog