Search code examples
javascripthtmlrowdelete-row

Add and delete row in the table


I am trying to write code for a table consisting of a textbox and a dropdownlist and a delete button on each row.

When the user click "Add Row" it adds another row that has the same elements on the first row. When user click "delete", it will delete that specific row as shown in the image here:

add and delete row

Here is my code:

function deleteRow(r) {
            var i = r.parentNode.parentNode.rowIndex;
            document.getElementById("myTable").deleteRow(i);
        }

       function myCreateFunction(n) {
            var tr = n.parentNode.parentNode.cloneNode(true);
            document.getElementById('myTable').appendChild(tr);
       }

The HTML:

<table id="myTable">
        <tr>
          <td >
          <input type="text" style="width:100%" />   
          </td>
      <td>
          <select>
                  <option value="Beginner" >Beginner</option>
                  <option value="Intermediate" >Intermediate</option>
                  <option value="Advanced" >Advanced</option>
              </select>
      </td>
          <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
        </tr>

    </table>

    <input type="button" class="add" value=" Add Row " onclick="myCreateFunction(this)" />

Solution

  • It's because you are cloning not the tr but the parent of add row button, which is not a tr, but a parent with table in it. You just need to get first row of a table and clone it

    function deleteRow(r) {
      var i = r.parentNode.parentNode.rowIndex;
      document.getElementById("myTable").deleteRow(i);
    }
    
    function myCreateFunction(n) {
      var tr = document.getElementsByTagName('tr')[0].cloneNode(true);
      document.getElementById('myTable').appendChild(tr);
    }
    <table id="myTable">
      <tr>
        <td>
          <input type="text" style="width:100%" />
        </td>
        <td>
          <select>
            <option value="Beginner">Beginner</option>
            <option value="Intermediate">Intermediate</option>
            <option value="Advanced">Advanced</option>
          </select>
        </td>
        <td><input type="button" value="Delete" onclick="deleteRow(this)"></td>
      </tr>
    
    </table>
    
    <input type="button" class="add" value=" Add Row " onclick="myCreateFunction(this)" />