index is an integer that specifies the position of the row to insert (starts at 0). The value of -1 can also be used; which result in that the new row will be inserted at the last position.
You can use .eq()
and .after()
like this:
$('#my_table > tbody > tr').eq(i-1).after(html);
The indexes are 0 based, so to be the 4th row, you need i-1
, since .eq(3)
would be the 4th row, you need to go back to the 3rd row (2
) and insert .after()
that.
Try this:
var i = 3;
$('#my_table > tbody > tr:eq(' + i + ')').after(html);
or this:
var i = 3;
$('#my_table > tbody > tr').eq( i ).after(html);
or this:
var i = 4;
$('#my_table > tbody > tr:nth-child(' + i + ')').after(html);
All of these will place the row in the same position. nth-child
uses a 1 based index.
Note:
$('#my_table > tbody:last').append(newRow); // this will add new row inside tbody
$("table#myTable tr").last().after(newRow); // this will add new row outside tbody
//i.e. between thead and tbody
//.before() will also work similar
I know it's coming late but for those people who want to implement it purely using the JavaScript
, here's how you can do it:
tr
which is clicked.tr
DOM element.tr
parent node.HTML:
<table>
<tr>
<td>
<button id="0" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
<tr>
<td>
<button id="1" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
<tr>
<td>
<button id="2" onclick="addRow()">Expand</button>
</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
<td>abc</td>
</tr>
In JavaScript:
function addRow() {
var evt = event.srcElement.id;
var btn_clicked = document.getElementById(evt);
var tr_referred = btn_clicked.parentNode.parentNode;
var td = document.createElement('td');
td.innerHTML = 'abc';
var tr = document.createElement('tr');
tr.appendChild(td);
tr_referred.parentNode.insertBefore(tr, tr_referred.nextSibling);
return tr;
}
This will add the new table row exactly below the row on which the button is clicked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With