Dynamically Add/Remove rows in HTML table using JavaScript

A good web design involves the better user interaction and ability to fetch the data in a better way. For fetching user data, you may have to create a form wherein user can add multiple entries and submit them simultaneously.

Thus for this you will need a way to add or remove fields dynamically into the HTML page. In my previous article, I had discussed about the way one can add dynamic form components into the web page.

In this article we will create a user interface where user can add/delete multiple rows in a form using JavaScript.

First check the user interface.
dynamic-add-delete-row-table-javascript

In this example, we have created a table which will display our html components. On pressing Add Row, a dynamic row will be created and added in the table. And on selecting the checkbox and pressing Delete Row, the row will be removed.

Following is the source.

Code


%MINIFYHTML0807a36d9b5b28baf2d100f2c21f948410%


	

	

	
1

For adding dynamic row in table, we have used insertRow() method. This method will insert a row at position specified by the index arguement. Also for removing row, we have used deleteRow() method.
Note that for inserting dynamic row, we have to created cells by using row.insertCell() method.

Check the online demo.

Online Demo


Click here.

Add/Remove rows from table having Drop Down List

What if my table has a selectbox or drop down list and I want to implement add/remove row functionality? A lot of people asked me this question (you can check comment section), so I thought to update this article and add one more case. Adding / Removing rows in a table having drop down list.

Following is the code:


%MINIFYHTML0807a36d9b5b28baf2d100f2c21f948411%


	

	

	

Check the addRow() method in above code. I have edited this piece of code from our previous example. The addRow() method iterates through all the columns and copy the content of 1st column to new column. This way a new row is created which is exact copy of 1st row. Also the switch{} case in the code make sure that the value are not copied as it is. For example, if you have entered text “abc” in textbox of 1st row and you press Add Row button, the new row will be added and the textbox of this new row will have value “abc”. So to make sure the values are not copied, we have added the switch{} code.

You may want to comment the switch{} code if the copying of the values in newly added row if desired to you.

Online Demo


Click here.

Getting Submitted Form Values in PHP

The main purpose of above code is to take input from user and persist it in database. Hence we may want to submit the above form and fetch its values in PHP to store the data in database.

If you notice we have multiple input textboxes with the same name. So in order to get these values in PHP request parameter, we need to modify our HTML. We need to append [] at the end of name of each input boxes including select box.

Thus our textbox definition:


Will change into:


Also the checkbox and select box definition change to:




Once we have changed the HTML code, add a submit button at the end of the form and submit this form to Fetchrequest.php

Following will be the code to get the values from request in PHP and displaying them on screen:

 $b)
  echo "$chkbox[$a]  -  $txtbox[$a]  -  $country[$a] 
"; ?>

If you read this far, you should follow me on twitter here.



478 Comments

  • Chris 18 November, 2013, 18:41

    Hi, I trying use your code to add rows. And I get error:

    Uncaught TypeError: Cannot read property ‘rows’ of null

    How to resolve that?

  • Panda 19 November, 2013, 16:14

    I need the numbers should be in sequence after deleted some rows… Please assist…Thanks in Adv….

    Panda

  • Sunil Pachlangia 21 November, 2013, 18:23

    How can i insert rows in a table in javascript using timing Events like setInterval() and setTimeout()

  • waseem Akram 22 November, 2013, 15:17

    Hi viral,
    i am trying to fetch data generated dynamically and store in mysql database
    using jsp.
    i am able to create dynamic rows with textboxes how can i store it in database??
    please help me out as soon as possible

    thnks best regards
    waseem

  • saravanan 25 November, 2013, 14:20

    hai viral
    In this “Dynamically Add/Remove rows in HTML table using JavaScript”:
    Add Three more column like Rate and quantity and multiple value placed in price column.
    important: the country column value fetch from mysql using php.
    plz help.

  • saravanan 25 November, 2013, 15:05

    hi viral
    i need small invoice page items are fetch from data base,add more item row dynamically like above articles.
    plz help me

  • Abhishek 28 November, 2013, 16:20

    hello,
    Please help me for adding the calender in dynamically added row in html using java script

  • Dhaval Vaja 17 December, 2013, 15:57

    i have prepared image of my que how can i upload my image on this site pls help….

  • bala 18 December, 2013, 11:38

    how to receive a data after submitting using jsp

  • Sun 19 December, 2013, 1:01

    Really Great code…!! helped me a lott….!!

  • Yin 27 December, 2013, 8:04

    hi,

    can i know how we can get the content of the specific deleted cell?

  • Jeff 31 December, 2013, 3:47

    Works simple and easy to follow. Thank you, this is exactly what I was looking for!
    Best wishes

  • simanta 6 January, 2014, 18:04

    hi I tried using the code but few hours everything was working fine but after some time the delete functionality is not working I know it sounds strange but can you please help.
    I just copied the whole code and then build my application

    thanks

  • Harjiv 12 January, 2014, 12:21

    Viral,
    Your add/delete rows program is not working correctly.
    When you click add row, it adds

  • vamshi 20 January, 2014, 12:36

    hi Viral,

    For this, Add/Remove rows from table having Drop Down List example above….
    Please tell me how to take and pass the values of textbox and dropdown list value to another servlet/jsp.

    Please help me with the code.

  • anghel vega 24 January, 2014, 13:17

    thsi working alone, buy if you paste this into
    NOT WORKING!!!!!!

  • faisal 7 February, 2014, 12:05

    hi i am using this code its working fine but i use date picker in it first row working with datepicker is well 2nd row can not accept datepicker class

    • fairuz 11 November, 2014, 14:07

      Same like me. how to solve for 2nd..3rd.row.. not working

  • sudhakar 27 February, 2014, 20:50

    Hi Viral,thank s for your help. my requirement is first with out showing empty row only when pressed the ADD Row button it needs to display. Thanks Sudhakar.

  • gu1ms 27 February, 2014, 21:37

    Thanks for this nice demo, exactly what I was looking for :)

  • hartej 25 March, 2014, 15:36

    thanks nice demo,my requirement is for row I kept some java script function which will perform some mathematical function which should be applicable for the newly added rows..my code will look like this.

    Priya Multispeciality Hospital

    jQuery(function(){
    var counter = 1;
    jQuery(‘a.add-author’).click(function(event){
    event.preventDefault();
    counter++;
    var newRow = jQuery(”);
    jQuery(‘table.authors-list’).append(newRow);

    });
    });

    function calculate()
    {
    var unit_cost = document.calc.unit_cost.value;
    var quantity =document.calc.quantity.value;
    var tax= document.calc.tax.value ;
    var total= document.calc.total.value ;

    document.calc.total.value=(parseInt(unit_cost) * parseInt(quantity)) + parseInt(tax);
    }

    ${msg}

    Add Drug

    Medicine Code
    Medicine Name
    Exp Date
    Unit Cost
    Quantity
    Tax
    Total
    Options

    +

    Add Drug

  • dumetro 28 March, 2014, 13:59

    Hie
    i have added several cells and their corresponding cases in that switch statement, but when i click the add row button it shows that its adding the rows but nothing is visible, its only my Div tag that expanding, where could i be wrong. Here’s the source code

    .cells.length;
     
     
                for(var i=0; i<colCount; i++) {
     
                    var newcell = row.insertCell(i);
     
                    newcell.innerHTML = table.rows[0].cells[i].innerHTML;
                    //alert(newcell.childNodes);
                    switch(newcell.childNodes[0].type) {
          				
    					case "checkbox":
                                newcell.childNodes[0].checked = false;
                                break;
    					case "date":
                                newcell.childNodes[0].value = "";
                                break;
    					case "time":
                                newcell.childNodes[0].value = "";
                                break;
    					case "select-one":
                                newcell.childNodes[0].value = "";
                                break;
    					case "select-one":
                                newcell.childNodes[0].value = "";
                                break;
    					case "select-one":
                                newcell.childNodes[0].value = "";
                                break;
    					case "text":
                                newcell.childNodes[0].value = "";
                                break;
    					case "text":
                                newcell.childNodes[0].value = "";
                                break;
    					case "text":
                                newcell.childNodes[0].value = "";
                                break;
    					case "text":
                                newcell.childNodes[0].value = "";
                                break;
    					case "text":
                                newcell.childNodes[0].value = "";
                                break;
    					case "text":
                                newcell.childNodes[0].value = "";
                                break;
    					case "textarea":
                                newcell.childNodes[0].value = "";
                                break;
    					case "text":
                                newcell.childNodes[0].value = "";
                                break;
                        case "select-one":
                                newcell.childNodes[0].selectedIndex = 0;
                                break;
                    }
                }
    		   
    		  
           }
    
           function deleteRow(autoTable) {
                try {
                var table = document.getElementById("autoTable");
                var rowCount = table.rows.length;
     
                for(var i=0; i<rowCount; i++) {
                    var row = table.rows[i];
                    var chkbox = row.cells[0].childNodes[0];
                    if(null != chkbox && true == chkbox.checked) {
                        if(rowCount <= 1) {
                            alert("Cannot delete all the rows.");
                            break;
                        }
                        table.deleteRow(i);
                        rowCount--;
                        i--;
                    }
     
     
                }
                }catch(e) {
                    alert(e);
                }
            }
    
        </SCRIPT>
    ]
    • java script coder 1 April, 2014, 17:26

      function addRow(cur) {
      try{
      var current = cur;

      while ( current.tagName !=”TABLE” )
      {
      //alert(current.id);
      current=current.parentElement;
      }
      //alert(“id”+current.id);
      var table = document.getElementById(current.id);

      var rowCount = table.rows.length;
      var row = table.insertRow(rowCount);

      var colCount = table.rows[0].cells.length;

      alert(“cols”+colCount);
      for(var i=0; i<colCount; i++) {

      var newcell = row.insertCell(i);

      newcell.innerHTML = table.rows[0].cells[i].innerHTML;

      //alert(newcell.childNodes);
      /*switch(newcell.childNodes[0].type) {
      case "text":
      newcell.childNodes[0].value = "";
      break;
      case "checkbox":
      newcell.childNodes[0].checked = false;
      break;
      case "select-one":
      newcell.childNodes[0].selectedIndex = 0;
      break;
      }*/
      }
      }
      catch(r)
      {
      alert(r.message);
      }
      }

  • kittu 1 April, 2014, 12:53

    please help this code..on click delete img,row should get delete and on blur every 4th child text box ,next row should be created

    <html>
    <head>
    <script>
    function myFunction(tableID)
    {
    var table = document.getElementById(tableID)
    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);
    
    var cell1 = row.insertCell(0);
    var element1 = document.createElement("img");
    element1.src= "del.gif";
    cell1.appendChild(element1);
    
    var cell2 = row.insertCell(1);
    var element2 = document.createElement("input");
    element2.type="text";
    cell2.appendChild(element2);
    
    var cell3 = row.insertCell(2);
    var element3 = document.createElement("input");
    element3.type="text";
    cell3.appendChild(element3);
    
    var cell4 = row.insertCell(3);
    var element4 = document.createElement("input");
    element4.type="text";
    cell4.appendChild(element4);
    cell4.element4.onblur="myFunction()";
    }
    
    
    function delfun(tableID)
     {
         document.getElementById("tab1").deleteRow();
                        
    }
    
    
    </script>
    </head>
    
    <body>
    <table id="tab1" border="1px"><tr>
    
    <td><img src="del.gif" id="delete" onclick="delfun(tab1)"></img></td>
    <td><input type="text" id="fname" /></td>
    <td><input type="text" id="mname" /></td>
    <td><input type="text" id="lname" onblur="myFunction('tab1')"/></td>
    </tr></table>
    </body>
    </html>
    
    
  • Zaa 2 April, 2014, 22:45

    Hello
    How keeping values in the table form after submit button on same page ?
    Thanks from France!
    Zaa

  • zaa 5 April, 2014, 6:29

    Thanks for code!
    How to display 4 empty rows with the add button under the table ? Thanks a lot !

  • sandun 7 April, 2014, 8:57

    can you help me to insert dynamic row data to database???i want PHP cording for insert data

  • Maruthi 7 April, 2014, 23:08

    i want to do autopopulate for added rows not happening please help.its happening for only one row

  • Maruthi 7 April, 2014, 23:13

    i want to do autopopulate for added rows for first row its happening only one row but not happening for newley added rows please help.Below code iam posting

    <link rel="stylesheet" type="text/css" href="/content/images/Button.css” />
    <link rel="stylesheet" type="text/css" href="/content/images/states.css” />

    var customarray123 = new Array();
    function addRow(tableID) {

    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var cell1 = row.insertCell(0);
    var element1 = document.createElement(“input”);
    element1.type = “checkbox”;
    element1.name=”chkbox[]”;
    cell1.appendChild(element1);

    var cell2 = row.insertCell(1);
    cell2.innerHTML = rowCount + 1;

    var cell3 = row.insertCell(2);
    var element2 = document.createElement(“input”);
    element2.type = “text”;
    element2.name = “txtbox[]”;
    cell3.appendChild(element2);

    var cell4 = row.insertCell(3);
    var element3 = document.createElement(“input”);
    element3.type = “text”;
    element3.name = “txtbox[]”;
    cell4.appendChild(element3);

    var cell5 = row.insertCell(4);
    var element4 = document.createElement(“input”);
    element4.type = “text”;
    element4.name = “txtbox[]”;
    cell5.appendChild(element4);

    var cell6 = row.insertCell(5);
    var element5 = document.createElement(“input”);
    element5.type = “text”;
    element5.name = “txtbox[]”;
    cell6.appendChild(element5);

    }

    <%
    String sTemp="";
    if(projnums!=null)
    {
    for (int index = 0; index
    customarray123[] = “”;

    function sample()
    {
    var v = document.getElementById(“ProjectNumberId”).value;
    alert(v);
    }
    //Added code for FM_Time sheet starts

    function getProjectDetails(projectNumber)
    {
    var selecteTOObj = document.getElementById(“ProjectNumberId”);
    if(selecteTOObj!=undefined)
    {
    var toSelectedEID = selecteTOObj.value;
    alert(toSelectedEID);
    var url = ‘getSelectprojectDetails.action?projectNumber=’+toSelectedEID;

    alert(url);
    var vehicleTestOwnerHttpReq;
    vehicleTestOwnerHttpReq = getAjaxHttpRequest();
    vehicleTestOwnerHttpReq.onreadystatechange = function() {
    if(vehicleTestOwnerHttpReq.readyState == 4) {
    if(vehicleTestOwnerHttpReq.status == 200) {
    var textResponse = vehicleTestOwnerHttpReq.responseText;
    document.getElementById(‘showNVHTestOwnerRelatedData’).innerHTML = textResponse;
    } else
    {
    document.getElementById(‘showNVHTestOwnerRelatedData’).innerHTML = “Error while loading NVH Requests”;
    }
    }
    };
    vehicleTestOwnerHttpReq.open(“GET”,url,true);
    vehicleTestOwnerHttpReq.send(null);
    }
    }

    //Added code for FM_Time sheet ends

    1

    var obj = new actb(document.getElementById(‘ProjectNumberId’),customarray123);

    <!– –>

  • xp 8 April, 2014, 21:44

    Gracias me sirvió mucho

  • Pavan 11 April, 2014, 11:40

    Hello Wonderful Article,it helped me a lot…But how to add this dynamically added row into the database using JDBC Servlets…Please help me out with this issue…

  • Janani 16 April, 2014, 18:18

    I want to add “id” for the input text . How do i add?

  • abhi 28 April, 2014, 20:38

    thanks for all ……this is really very helpful for my type of beginers

  • Illy 8 May, 2014, 21:07

    Hi,

    post is very helpful, but in your Demos button Delete is not working.

    BR

  • Andrej 14 May, 2014, 15:05

    Many thanks for the code but found an error! :)

    <TR>
                <TD><INPUT type="checkbox" name="chk"/></TD>
                <TD><INPUT type="text" name="txt"/></TD>
                <TD>
                    <SELECT name="country">
                        <OPTION value="in">India</OPTION>
                        <OPTION value="de">Germany</OPTION>
                        <OPTION value="fr">France</OPTION>
                        <OPTION value="us">United States</OPTION>
                        <OPTION value="ch">Switzerland</OPTION>
                    </SELECT>
                </TD>
    

    You shouldn’t use any space or newline between and because now newcell.childNodes[0].type returns “undefined” because first childNode in cell of OPTION is text!

    SOLUTION:

    <TR>
                <TD><INPUT type="checkbox" name="chk"/></TD>
                <TD><INPUT type="text" name="txt"/></TD>
                <TD><SELECT name="country">
                        <OPTION value="in">India</OPTION>
                        <OPTION value="de">Germany</OPTION>
                        <OPTION value="fr">France</OPTION>
                        <OPTION value="us">United States</OPTION>
                        <OPTION value="ch">Switzerland</OPTION>
                    </SELECT>
                </TD>
    
  • Gautam 17 May, 2014, 17:32

    hii….how would you save the data of dynamically generated rows in database????

  • Gautam 20 May, 2014, 20:49

    how to save the dynamically genrated row in database?

  • Zoidberg 26 May, 2014, 10:07

    Thanks! This was very helpful!

  • Me 1 June, 2014, 21:11

    Thanks bro this is very very very very helpful

  • kishan 16 June, 2014, 18:41

    how to save get and save this data in database

  • Kishan 17 June, 2014, 11:13

    how to insert data in database table ?
    And hoe to get data in viable And display it…?
    Rply fast

    • Shahid Aziz 25 June, 2014, 17:17

      Here is a complete code with database and working fine.

      Add/Remove dynamic rows in HTML table

      function addRow(tableID) {

      var table = document.getElementById(tableID);

      var rowCount = table.rows.length;
      var row = table.insertRow(rowCount);

      var colCount = table.rows[0].cells.length;

      for(var i=0; i<colCount; i++) {

      var newcell = row.insertCell(i);

      newcell.innerHTML = table.rows[1].cells[i].innerHTML;
      //alert(newcell.childNodes);
      switch(newcell.childNodes[0].type) {
      case "text":
      newcell.childNodes[0].value = "";
      break;
      case "checkbox":
      newcell.childNodes[0].checked = false;
      break;
      case "select-one":
      newcell.childNodes[0].selectedIndex = 0;
      break;
      }
      }
      }

      function deleteRow(tableID) {
      try {
      var table = document.getElementById(tableID);
      var rowCount = table.rows.length;

      for(var i=0; i<rowCount; i++) {
      var row = table.rows[i];
      var chkbox = row.cells[0].childNodes[0];
      if(null != chkbox && true == chkbox.checked) {
      if(rowCount <= 2) {
      alert("Cannot delete all the rows.");
      break;
      }
      table.deleteRow(i);
      rowCount–;
      i–;
      }

      }
      }catch(e) {
      alert(e);
      }
      }

      Item
      Quantity
      Cost

      <OPTION value=”in”>India
      <?php

      $con=mysql_connect('localhost','root','');
      // Check connection
      if (mysql_errno())
      {
      echo "Failed to connect to mysql: " . mysql_connect_error();
      }

      mysql_select_db("MNR");
      $result = mysql_query("SELECT * FROM inventory");

      while($row = mysql_fetch_assoc($result))
      {
      $pid=$row['ItemID'];
      $name=$row['Item_Name'];
      // print "$fn\n”;
      echo “$name”;

      }
      ?>

      $value)
      {
      $item = $_POST[“item”][$key];
      $price = $_POST[“cost”][$key];
      $qty = $_POST[“qty”][$key];
      //$total=$price*$qty;
      // $d= $_POST[‘item’];
      $cartage=20;
      $rows=$_POST[“item”][$key];
      $total=($cartage/$rows);
      $con=mysql_connect(‘localhost’,’root’,”);

      // Check connection
      if (mysql_errno())
      {
      echo “Failed to connect to mysql: ” . mysql_connect_error();
      }

      mysql_select_db(“MNR”);

      $query = “INSERT INTO purchasedetail(ItemCode,Quantity,UnitCost,Total) VALUES(‘$item’,’$qty’,’$price’,’$total’)”;

      if (!mysql_query($query))
      {
      die(‘Error: ‘ . mysql_error($con));
      }
      }}
      ?>

  • gurram mahesh bau 23 June, 2014, 16:25

    function addRow(tableID) {

    var table = document.getElementById(tableID);

    var rowCount = table.rows.length;
    var row = table.insertRow(rowCount);

    var colCount = table.rows[0].cells.length;

    for(var i=0; i<colCount; i++) {

    var newcell = row.insertCell(i);

    newcell.innerHTML = table.rows[0].cells[i].innerHTML;
    //alert(newcell.childNodes);
    switch(newcell.childNodes[0].type) {
    case "text":
    newcell.childNodes[0].value = "";
    break;
    case "checkbox":
    newcell.childNodes[0].checked = false;
    break;
    case "select-one":
    newcell.childNodes[0].selectedIndex = 0;
    break;
    }
    }
    }

    function deleteRow(tableID) {
    try {
    var table = document.getElementById(tableID);
    var rowCount = table.rows.length;

    for(var i=0; i<rowCount; i++) {
    var row = table.rows[i];
    var chkbox = row.cells[0].childNodes[0];
    if(null != chkbox && true == chkbox.checked) {
    if(rowCount <= 1) {
    alert("Cannot delete all the rows.");
    break;
    }
    table.deleteRow(i);
    rowCount–;
    i–;
    }

    }
    }catch(e) {
    alert(e);
    }
    }

    Sl no
    Item Name
    Item Code
    Description
    Qty
    Unit Price
    Total

    ${sessionScope.item_code}
    ${sessionScope.description}

    ${sessionScope.unit_price}

  • vanisree 27 June, 2014, 15:14

    Hi Viral,
    Is there any way to create dynamic tables as like adding new rows to table.

    Thanks
    Vanisree

  • Madhuri 14 July, 2014, 17:34

    hi, I am also working on dynamically adding table row using jsp, but i am getting one exception in that : whenever in a table there is only one row and i submit, it trough’s an error , but works fine when i add row that means when there’s total 2 row in a table.
    can anybody help me resolve this issue …

  • mohammed 15 July, 2014, 12:10

    Hi .. .U r tutorial is helping alot . . . i need the code to fetch the data in database from added and deleted text boxes using servlet or jsp plz help me out

  • Media Dewi 26 August, 2014, 15:22

    Dear, Viral!
    Thanks a lot for posting really great tutorials. I’m trying to apply your tutorial titled ‘Add/Remove rows from table having Drop Down List’, and I wonder how to save or insert the data from the table into mysql database. I hope you’d be able to explain here. Thanks a lot :)

  • tester 26 September, 2014, 20:26

    You should clean the code it is not clear and difficult to read
    e.g. variable names, blank lines, bad indentation (try/catch), html tags uppercase

  • Abdullahi M A 14 October, 2014, 20:36

    Please is there a way I could restrict the maximum number of rows allowed, disable the add buttom if maximum is reached

  • amareal 20 October, 2014, 3:13

    This is a beautiful tutorial, please how can i restrict the number of rows that can be add, disable the add button if maximum is reached.
    Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

Note

To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]