I need to split a table into two tables at a particular row number using jQuery. Can this be done?
I googled but couldn't find anything. jQuery's pretty powerful, I would have thought this can be done.
The table is not numbered so jQuery would need to index the rows.
Any help with this is very much appreciated.
C
jQuery Slice method will be useful in such case: documentation here
Add a table with some rows in html:
<table id="mainTable">
<tr>
<td>Row 1</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 2</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 3</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 4</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 5</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 6</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 7</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 8</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 9</td>
<td>Dummy Data</td>
</tr>
<tr>
<td>Row 10</td>
<td>Dummy Data</td>
</tr>
</table>
Slice n rows using jQuery, create new table instance and append rows:
<script type="text/javascript">
jQuery(document).ready(function() {
var $mainTable = $("#mainTable");
var splitBy = 5;
var rows = $mainTable.find ( "tr" ).slice( splitBy );
var $secondTable = $("#mainTable").parent().append("<table id='secondTable'><tbody></tbody></table>");
$secondTable.find("tbody").append(rows);
$mainTable.find ( "tr" ).slice( splitBy ).remove();
});
</script>
See working demo here
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