Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery split a table into two tables at a particular row number

Tags:

html

jquery

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

like image 602
Cybercampbell Avatar asked Feb 14 '23 14:02

Cybercampbell


1 Answers

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

like image 185
Dharmang Avatar answered Feb 16 '23 03:02

Dharmang