Reputation: 32331
When the labels are clicked, i am showing dynamic data and this is working fine with table sorter. Clicking on the table headers is sorting the table rows.
The issue i am facing is, after clicking the label "One" and then clicking on label "Two", and trying to sort data from the second response, it stops working from here onwards.
This is my code:
$(document).on("click", ".candlespattern", function() {
var clicked = $(this).attr("id");
var datatoselect = '';
if (clicked === 'one') {
datatoselect = myjsonresponse1;
} else if (clicked === 'two') {
datatoselect = myjsonresponse2;
}
var html = "";
html += '<thead><th class="thheaders">Symbol</th><th class="thheaders">Date</th></thead><tbody>';
for (var e = 0; e < datatoselect.length; e++) {
html += "<tr><td>" + datatoselect[e].name + "</td><td>" + datatoselect[e].date_time + "</td></tr>"
}
$("#candletable").html(html);
$('#candletable').tablesorter({}).tablesorterPager({
container: $(".pager"),
size: 20
});
$("#candletable").trigger("update");
$("#pager").show();
});
Upvotes: 2
Views: 1196
Reputation: 35491
Ok so after researching this particular plugin, I came across a useful example.
First of all, your problem is most likely that you are overwriting the thead
of the table each time the item is clicked leading to the plugin to lose some references. Here's how I suggest you do it:
Since the thead
is the same for both responses, there's no need to add it dynamically each time and we can just put it in the HTML:
<table id="candletable" class="table table-striped tablesorter">
<!-- add the table head and an empty tbody -->
<thead>
<th class="thheaders">Symbol</th>
<th class="thheaders">Date</th>
</thead>
<tbody>
</tbody>
</table>
Next thing is that we should initialize the tablesorter
only once, and then just update the data:
$(document).ready(function() {
// initialize the table sorter on document.ready
$('#candletable').tablesorter({}).tablesorterPager({
container: $(".pager"),
size: 20
});
$("#pager").hide();
});
Finally, we remove the thead
data and the initialization from the click handler and add the created table rows to tbody
:
$(document).on("click", ".candlespattern", function() {
var clicked = $(this).attr("id");
var datatoselect = '';
if (clicked === 'one') {
datatoselect = myjsonresponse1;
} else if (clicked === 'two') {
datatoselect = myjsonresponse2;
}
// create the table rows from the response
var html = "";
for (var e = 0; e < datatoselect.length; e++) {
html += "<tr><td>" + datatoselect[e].name + "</td><td>" + datatoselect[e].date_time + "</td></tr>"
}
// add the rows to table body
$("#candletable tbody").html(html);
// update the table
$("#candletable").trigger("update");
// show it
$("#pager").show();
});
Upvotes: 2