Reputation: 221
Is there any way to insert a row on a specific place in the table. The user will input a number where he/she wants the row to be inserted.
Let's say that the user wants the row to be inserted on the second row of the tbody of the table.
<tr>
<td>00001</td>
<td>John</td>
</tr>
The table I have
<tr>
<td>00002</td>
<td>David</td>
</tr>
<!-- Here is where I want it to be insterted -->
<tr>
<td>00004</td>
<td>Frank</td>
</tr>
<tr>
<td>00005</td>
<td>Jane</td>
</tr>
Upvotes: 1
Views: 1481
Reputation: 19070
You can select the tr:first
element and than .after() to add your new element:
$('table tr:first').after('<tr><td>00001</td><td>John</td></tr>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>00002</td>
<td>David</td>
</tr>
<!-- Here is where I want it to be insterted -->
<tr>
<td>00004</td>
<td>Frank</td>
</tr>
<tr>
<td>00005</td>
<td>Jane</td>
</tr>
</table>
Upvotes: 0
Reputation: 33218
An approach could be by adding a method in jquery prototype object for example:
// a method to add row after specific row
$.prototype.addTableRowAfter = function(row, element) {
// here you can modify it to a more general approach
this.find('tr:eq(' + row + ')').after(element);
return this;
};
// call it
$('table').addTableRowAfter(0, '<tr><td> 00001</td><td>John</td ></tr>');
$('table').addTableRowAfter(2, '<tr><td> 00003</td><td>Jim</td ></tr>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>00002</td>
<td>David</td>
</tr>
<!-- Here is where I want it to be insterted -->
<tr>
<td>00004</td>
<td>Frank</td>
</tr>
<tr>
<td>00005</td>
<td>Jane</td>
</tr>
</tbody>
</table>
Upvotes: 0
Reputation: 12864
You can use the method after
to insert html,
and to insert in the right place you can use CSS pseudo-class :nth-child
$("table > tbody > tr:nth-child(2)").after('<tr><td>Example</td></tr>');
In my example you insert after the second tr tag.
Upvotes: 1