Question

I'm trying to add a new set of rows below the original one's and have a delete function together w/ the add function. Luckily I bumped into an article of w3schools : http://www.w3schools.com/jsref/met_table_insertrow.asp

However it adds the new cells above the original one's, how can I tweak it to make it work?

CODE:

<table id="myTable" border="1">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
<tr>
<td>Row3 cell1</td>
<td>Row3 cell2</td>
</tr>
</table><br>

<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>

<script>
function myCreateFunction()
{
var table = document.getElementById("myTable");
  {
  var row = table.insertRow(0);
  var cell1 = row.insertCell(0);
  var cell2 = row.insertCell(1);
  cell1.innerHTML = "NEW CELL1";
  cell2.innerHTML = "NEW CELL2";
  }
}
function myDeleteFunction()
{
document.getElementById("myTable").deleteRow(0);
}
</script>
Was it helpful?

Solution 4

var row = table.insertRow(0); // 0 represent the 0th index and hence it add at top

change it to

var tdsLength = table.getElementsByTagName('tr').length;
var row = table.insertRow(tdsLength);  //change it to last index

or

var row = table.insertRow(-1);

From Docs, If index is -1 or equal to the number of rows, the row is appended as the last row. JSFiddle

OTHER TIPS

insertRow() takes the position of the new row as an (optional) parameter. So, if you want the new row at the end of the table, insert an according index like this:

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

Example Fiddle

In your code you set an index of 0, which by definition is the first row.

Here's the jQuery solution.... if you want it.

HTML

<table border="1" id="myTable">
    <thead>
        <tr>
            <td>Col 1</td>
            <td>Col 2</td>
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

<br>
<input type="button" onclick="addRow()" value="Add row" />

JavaScript

var rowNo = 1;
function addRow()
{
    $('#myTable tbody').append('<tr><td>Row #'+ rowNo +'</td>'+
                               '<td>Row #'+ rowNo +'</td></tr>');
    rowNo++;    
}

Live Demo

If you are using jQuery then use .after() with :eq(int) and for removing you can use .remove() but if you want to remove only newly added rows then you can use :gt(int) method:

$(function () {
   $('#create').on('click', function () {
      var table = $('#myTable')[0];
      var rows = table.rows.length;
      var row = '<tr><td>'+ rows +'</td><td>'+ rows +'</td></tr>';
      $('#myTable').find('tr:eq(2)').after(row);
   });
   $('#delete').on('click', function () {
      $('#myTable').find('tr:gt(2)').get(0).remove();
   });
});

Using the above script you have to give your buttons specific ids #create for row creation and #delete for delete button like suggested below.

<button id='create'>Create row</button>
<button id='delete'>Delete row</button>

Note:

Unobtrusive javascript is better. Inline scripting should be avoided.

Demo fiddle


Updates:

Instead of hardCode in :eq(2) and :gt(2) we can cache the length of the trs in table:

$(function () {
   var o = $('#myTable').find('tr:last').index(); // cache it here
   $('#create').on('click', function () {
      var table = $('#myTable')[0];
      var rows = table.rows.length;
      var row = '<tr><td>' + rows + '</td><td>' + rows + '</td></tr>';
      $('#myTable').find('tr:eq(' + o + ')').after(row); // place it here
   });
   $('#delete').on('click', function () {
      $('#myTable').find('tr:gt(' + o + ')').get(0).remove(); // and here
   });
});

Demo fiddle with cached trs


$('#myTable').find('tr:last').index(); this line gets the last tr's index at the dom ready which is in this case 2 because .index() is 0 based.

Change the code in:

var row = table.insertRow(0);

to:

var row = table.insertRow(-1);

Maybe use jQuery .prepend() function? Check it here: http://api.jquery.com/prepend/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top