Interview Questions

JavaScript - Add table rows dynamically

To add rows dynamically to a HTML table use the following Java Script code.

<html>
<body>

<script type="text/javascript">
function addRow()
{
      var num = document.getElementById('sequenceId');
      var table = document.getElementById('dynamicTable');
     
      var table = document.getElementById('dynamicTable');
      var val = num.value * 1;

      for(i=0;i<val;i++)
      {
             var rowCount = table.rows.length;
             var row = table.insertRow(rowCount);
             var cell3 = row.insertCell(0);
             var element2 = document.createElement("input");
             element2.type = "text";
             cell3.appendChild(element2);
       }
}
</script>

<form>
   <label>No. of Rows</label>
   <input type="text" id="sequenceId" name="sequence"   onchange="addRow();"/>
   <table id="dynamicTable" border="1">
   </table>
</form>

</body>
</html>