Reputation: 1623
I have a huge table that I want to clone and divide the clone into 2 separate tables, keeping the original table unchanged.
Say the original table is called #MainTable with 10 columns
I create a clone #CloneTable which initially also has all the 10 columns of #MainTable
Now, I change #CloneTable, such that #CloneTable has the first 5 columns and another table #RemainingClone has the remaining 5 columns
Now, what happens here is that suddenly my original table #MainTable also loses 5 columns and updates to retain only those columns that #CloneTable has.
Shouldn't #MainTable be unaffected by changes being made to #CloneTable?
EDIT 1: I am using the jquery clone(), as the Tags indicate.
$("#MainTable").clone().attr('id', 'CloneTable').appendTo("#printingDiv");
splitTable();
function splitTable() {
var divider = 5;
var $tableOne = $('table').attr('id','CloneTable');
var $tableTwo = $tableOne.clone().attr('id','RemainingClone').appendTo('#printingDiv');
// number of rows in table
var numOfRows = $tableOne.find('tr').length;
// select rows of each table
var $tableOneRows = $tableOne.find('tr');
var $tableTwoRows = $tableTwo.find('tr');
// loop through each row in table one.
// since table two is a clone of table one,
// we will also manipulate table two at the same time.
$tableOneRows.each(function(index){
// save row for each table
var $trOne = $(this);
var $trTwo = $tableTwoRows.eq(index);
// remove columns greater than divider from table one
$trOne.children(':gt('+divider+')').remove();
$trTwo.children(':lt('+(divider+1)+')').remove();
});
}
Upvotes: 0
Views: 1822
Reputation: 9930
Here's a fiddle that shows a way of doing what you describe: DEMO. I'm not seeing the behavior you describe (i.e. the original is modified along with some of its clones).
JS
$(function() {
var firstFive = $('#main').clone();
var secondFive = $('#main').clone();
$('body').append(firstFive);
$('body').append(secondFive);
firstFive.find('tr').each(function() {
$(this).find('td:gt(4)').remove()
});
secondFive.find('tr').each(function() {
$(this).find('td:lt(5)').remove()
});
})
HTML
<table id="main">
<tr>
<td>1.1</td>
<td>1.2</td>
<td>1.3</td>
<td>1.4</td>
<td>1.5</td>
<td>1.6</td>
<td>1.7</td>
<td>1.8</td>
<td>1.9</td>
<td>1.10</td>
</tr>
<tr>
<td>2.1</td>
<td>2.2</td>
<td>2.3</td>
<td>2.4</td>
<td>2.5</td>
<td>2.6</td>
<td>2.7</td>
<td>2.8</td>
<td>2.9</td>
<td>2.10</td>
</tr>
</table>
Hope it helps.
EDIT: This was posted before the code sample.
Upvotes: 0
Reputation: 27637
In the splitTable()
function you are calling:
var $tableOne = $('table').attr('id','CloneTable');
This sets the ID of all <table>
elements to be 'CloneTable', including the one it was originally cloned from, being 'MainTable', and references both DOM elements. All changes to this jQuery object will now affect both tables. To just get the cloned table, you would use the following as you changed the ID when it was created:
var $tableOne = $('table#CloneTable');
Upvotes: 2