add or remove rows in a HTML table dynamically using javascript code

 HTML documents can be easily accessed and manipulated using HTML DOM, which represents an HTML document as a tree-structure.  When a  HTML document is  loaded in a browser window , it  becomes a Document object. Now we can use the Document object  to  access to all HTML elements  (as node objects) in a page, using  any script such as Javascript. Using  Document object ,  we can add or remove  element in the html as we do for  xml,  You can go through my earlier post to create xml using DOM.

             Let us see some of the following  HTML DOM properties and methods to access / modify the html documents , before writing the actual  program.
Some DOM properties:
nodeName – returns the name of an element
nodeValue – returns the value of an element
parentNode – returns the parent node of an element
childNodes – returns the child nodes of element
attributes – returns the attributes nodes of element
innerHTML –  to get or modify the content of  an element
   Suppose  x is a node object (HTML element), the above properties can be accessed  as  x.innerHTML , x.nodeName, ….
Similarly some DOM methods:
getElementsByTagName(name) – get all elements with a specified tag name
getElementById(id) – get the element with a specified id
appendChild(node) – insert a child node to the element
removeChild(node) – removes a child node from the element
eg. document.getElementById(“tableId”), returns the table object.  you can insert, row & columns using the table object.
to get the content (text)  of an element <p id=”test”>This is a test</p>, you can use   innerHTML OR   childNodes and nodeValue properties with the method   getElementById
txt = document.getElementById(“test”).innerHTML;
or 
 txt=document.getElementById(“test”).childNodes[0].nodeValue;

Now let us design HTML table  and write javascript code to add or remove rows in a table.   Consider the web page to accept passenger details and child passenger details for booking ticket in a train or bus. To accept, passenger details , we need to  insert  rows and columns in a table ,  based on the first row  of the table.  The first row is mandatory to accept at least one passenger details .


Table design with one row and heading

<h1>Passengers Details</h1>
<table id="PDetailsTable" border="1" width="350px">
<tbody>
<tr>
   <td>SNO</td>
   <td>Name</td>
   <td>Age</td>
   <td>Gender</td>
   <td>Food Preference</td>
   <td>Berth Preference</td>
   <td>Senior Citizen</td>
   <td>Select to Delete</td>
</tr>
<tr>
   <td>1</td>
   <td><input name="name" type="text" /></td>
   <td><input name="age" type="text" /></td>
   <td><select name="Gender">
   <option value="M">Male</option>
   <option value="F">Female</option>
   </select></td>
   <td><select name="Food">
    <option value="v">Veg</option>
    <option value="nv">Non-Veg</option>
    </select></td>
    <td><select name="BerthPreference">
    <option value="l">Lower</option>
    <option value="m">Middle</option>
    <option value="u">Upper</option>
    <option value="sl">Side Lower</option>
    <option value="su">Side Upper</option>
    </select></td>
    <td><input name="SCchk" type="checkbox" /></td>
    <td><input name="delchk" type="checkbox" /></td>
</tr>
</tbody>
</table>

Two input  buttons to call   addPassenger function  to insert dynamic row and to call deletePassengerRow  to remove row from the table dynamically.

 <input type="button" value="Add More Passengers" onclick="addPassenger('PDetailsTable')" />
 <input type="button" value="Delete Row" onclick="deletePassengerRow('PDetailsTable')" /> 

Two javascript functions  to add and remove dynamic rows and columns  and one more function ( arrangeSno)  to arrange serial numbers when the row is removed from the table are as follows

to arrange serial numbers

 function arrangeSno(tableId)

 {

             var tblObj = document.getElementById(tableId);

             var no_of_rows = tblObj.rows.length;

              for(var i=0; i<no_of_rows-1; i++)

          tblObj.rows[i+1].cells[0].innerHTML = i+1;

 }

To add rows dynamically based on the first row in a table 

      function addPassenger(tableId) {

            var tblObj = document.getElementById(tableId);

            var no_of_rows = tblObj.rows.length;
     

// to insert single row

            var row_in_table = tblObj.insertRow(no_of_rows);

// to get the number of colums from the first row

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

// to increment sno from the previous row by one

           var rno=eval(tblObj.rows[no_of_rows-1].cells[0].innerHTML) +1;

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

// to insert one column 

               var column_in_row = row_in_table.insertCell(i);

                column_in_row.innerHTML = tblObj.rows[1].cells[i].innerHTML;

                if (i==0)  column_in_row.innerHTML = rno;

// to fill new row with  blank  text box, unchecked checkbox ,  combo selected with index 0 when the row is created , eventhough  the first row of the table having the textbox with filled values , etc...

                switch(column_in_row.childNodes[0].type) {

                    case "text":

                            column_in_row.childNodes[0].value = "";

                            break;

                    case "checkbox":

                            column_in_row.childNodes[0].checked = false;

                            break;

                    case "select-one":

                            column_in_row.childNodes[0].selectedIndex =0;

                            break;

                }

            }

        }

To remove rows dynamically  from the table . 

        function deletePassengerRow(tableId) {

                    var tblObj = document.getElementById(tableId);

 
                 var delchkbox=document.bookingForm.delchk;    // where bookingForm is the form name

        var no_of_rows = delchkbox.length;

         for(var i=0; i<no_of_rows;i++)

         {

// heading and atleast one row should be in the table

        if (delchkbox[i].checked && tblObj.rows.length>=3) 

        {

           tblObj.deleteRow(i+1);

               no_of_rows--;

                i--;

             }

                }

          arrangeSno(tableId);        }  

To accept ,child  passenger details,  we are creating  elements like textbox, checkbox, dropdown list dynamically. These elements are inserted in the table’s columns in a row  as a child element. Table rows and columns are also created dynamically. No row is mandatory. Table heading is displayed, if the table has at least one row, otherwise, table heading is hidden.

Table design with heading without any initial rows 

<H1>Child Passengers Details</H1>

    <TABLE id="childPassTable" width="350px" border="1" style="visibility:hidden" >

        <tr>

         <td>SNO</td>

         <td>Name</td>

         <td>Age</td>

         <td>Gender</td>

         <td>Select to delete</td>

    </tr>         </TABLE> 

Two buttons to call  addRowForChild &  deleteRowChild

 <P> <input type ="button" value="Add Child Passengers"  onclick="addRowForChild('childPassTable')">
 <input type="button" value="Delete Row" onclick="deleteRowChild('childPassTable')"></P>

Two javascript functions to add rows / remove rows in a table  and to create textbox, checkbox, combo box dynamically  for accepting child passenger details.

    function addRowForChild(tableId) {

            var tblObj = document.getElementById(tableId);
 
            var no_of_rows = tblObj.rows.length;

// to make visible of the header row of the table , if the table has atleast one row
            if(no_of_rows==1)

             tblObj.style.visibility="visible";

// to insert one row of the table

            var row_in_table = tblObj.insertRow(no_of_rows);

//to insert the first column (for SNO)

            var column1 = row_in_table.insertCell(0);

      if (no_of_rows==1)
         var rno=1;

     else
        var rno=eval(tblObj.rows[no_of_rows-1].cells[0].innerHTML) +1;

            column1.innerHTML = rno;

//to insert the second column (for textbox to accept name)

            var column2 = row_in_table.insertCell(1);

            var element2 = document.createElement("input");

            element2.setAttribute("name", "nameChild");  //to set name of the text box

            element2.type = "text";

            column2.appendChild(element2);

 //to insert the second column (for textbox to accept age)
            var column3 = row_in_table.insertCell(2);

            var element3 = document.createElement("input");

            element3.setAttribute("name", "ageChild");

            element3.type = "text";

            column3.appendChild(element3);

 //to insert the fourth column (for combo box to select gender)

            var column4 = row_in_table.insertCell(3);

            var combo = document.createElement("select");

            combo.setAttribute("name", "genderChild"); 

            var option = document.createElement("option");

            combo.options[0] = new Option("Male", 1);

             combo.options[1] = new Option("Female", 2);

            column4.appendChild(combo);

// to insert the fifth column (for check box )  

            var column5 = row_in_table.insertCell(4);

           var element5 = document.createElement("input");

            element5.type="checkbox";

            column5.appendChild(element5);
        }

       function deleteRowChild(tableId) {

            var tblObj = document.getElementById(tableId);

            var no_of_rows = tblObj.rows.length;

            var i=0;

            while (i<no_of_rows)

            {

                var row_in_table = tblObj.rows[i];

                var chkbox = row_in_table.cells[4].childNodes[0];

                if( chkbox !=null &&  chkbox.checked==true) {

                    tblObj.deleteRow(i);

                    no_of_rows--;

                    i--;

// to hide the table heading , if there is no row

            if(no_of_rows<=1) tblObj.style.visibility="hidden";

                }

                i++;

                }

             arrangeSno(tableId);

                   } 

Sample code to send / pass /  process the elements created  dynamically  in the page  to server side using servelet.

String[] names=request.getParameterValues("name");
String[] birthPreference=request.getParameterValues("BerthPreference");
String[] nameChild=request.getParameterValues("nameChild");
   .....
   .....
   .....
       for (int i = 0; i < names.length; i++)
          System.out.println("Name=" + names[i] + " Birth Preferance= " +  birthPreference[i] );

……. ……..

Try Live Demo

Leave a Reply