Adding HTML elements on click of a button

When I  was working on my college project, I wanted to  add textfields on click of a button, at first, I used innerHTML=”…” for doing that, but it didn’t work and I did it like this(credits to Ashish Shukla ):


<script type="text/javascript">
var i = 3;

function addField(tableid)
   var row = document.createElement("tr");
   var col1 = document.createElement("td");
   var col2 = document.createElement("td");
   var input = document.createElement("input");

   input.setAttribute("name","field" + i );

   col1.appendChild(document.createTextNode("Field" + i));


   var table = document.getElementById(tableid);




<form name="myform" action="myfile.php" method="post" id="myform">
<table id="fieldTable">

<tr><td>Field1 : </td><td><input type="text" name="field1" /></td></tr>
<tr><td>Field2 : </td><td><input type="text" name="field2" /></td></tr>
<tr><td><input type="button" value="Add field" id="button"  onclick="addField('fieldTable')" /></td>
<td><input type="submit"/></td></tr>


Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s