Reputation: 8970
I am having some issues that I can't seem to track down.
Order of Operations:
My Table has rows like so:
<tr data-area-count="2" data-region-count="2" data-regions="North America, EMEA" data-areas="Area 1, Area 2">
My jQuery:
// Global Vars
var results,
oTable;
$(function() {
results = $('[name=resultsTable]').clone();
});
There are several buttons on the page a user can filter the data by. When they click on the button, this is the function that is run:
// Depending on which region needs to be shown, toggle here.
function filterRegion(region) {
var data = results,
tempArray = Array(),
tempAreas,
tempRegions;
// Based on the region/option we selected..
switch (region) {
case 'EMEA':
// Append the data to the dom
$('.res').empty().append(data).find('table').addClass('dt');
// Loop over the rows
$('.res').find('.results tr').each(function() {
// Collect the values of each of the rows we interate over
tempRegions = $(this).data('regions');
tempArray = tempRegions.split(", ");
tempRow = $(this);
// Check to see if this case value exists in the array
if (jQuery.inArray('EMEA', tempArray) == -1) {
// the region is not in the array, remove the row
tempRow.remove();
};
});
break;
}
In the statement above, I expect it to append he original, untouched, version of the table that was initially loaded and then if EMEA
was not in the list of data-regions
, it would remove all of the rows from the table in the DOM.
However, it seems to be altering data in the global variable because when I toggle back between the different filters, I am eventually left with no data being appended to the DOM since its "removed" all the rows when hitting each of the filter statements.
I feel that I am cloning or using the cloned data incorrectly. Any thoughts?
Upvotes: 0
Views: 116
Reputation: 1706
From the json append documentation (https://api.jquery.com/append/):
If an element selected this way is inserted into a single location elsewhere in the DOM, it will be moved into the target (not cloned).
So I think in your append(data)
call you move the data from your global result variable there. Then later you remove elements from it (which modifies the global results DOM object). Instead you have to clone it once again. So I think replacing the line
var data = results,
with
var data = results.clone(),
should solve the problem. I didn't test it though.
Upvotes: 4