I’ve a code to sort table using Jquery.I use toggle function to alternate clicks,and toggle beetween ‘ascend’ and ‘descend’ sort.Once you click header’s table it should sort it contents.
However,there’s a bug:
I click once,it sorts,then when i click again,nothing happens.I need to click again (second time) to execute the second function,and sort again.
Toggle should switch functions with single clicks,not double,am i right?
Here is the code:
firstRow.toggle(function() {
$(this).find("th:first").removeClass("ascendFirst").addClass("descendFirst");
$(this).find("th:not(first)").removeClass("ascend").addClass("descend");
sorted = $.makeArray($("td:eq(0)", "tr")).sort().reverse();
sorted2 = $.makeArray($("td:eq(1)", "tr")).sort().reverse();
sorted3 = $.makeArray($("td:eq(2)", "tr")).sort().reverse();
for (var i = 0; i < sorted.length; i++) {
$("td", "tr:eq(" + (i + 1) + ")").remove();
$("tr:eq(" + (i + 1) + ")").append($("<td></td>").text($(sorted[i]).text()));
$("tr:eq(" + (i + 1) + ")").append($("<td></td>").text($(sorted2[i]).text()));
$("tr:eq(" + (i + 1) + ")").append($("<td></td>").text($(sorted3[i]).text()));
}
}, function() {
$(this).find("th:first").removeClass("descendFirst").addClass("ascendFirst");
$(this).find("th:not(first)").removeClass("descend").addClass("ascend");
sorted = $.makeArray($("td:eq(0)", "tr")).sort();
sorted2 = $.makeArray($("td:eq(1)", "tr")).sort();
sorted3 = $.makeArray($("td:eq(2)", "tr")).sort();
for (var i = 0; i < sorted.length; i++) {
$("td", "tr:eq(" + (i + 1) + ")").remove();
$("tr:eq(" + (i + 1) + ")").append($("<td></td>").text($(sorted[i]).text()));
$("tr:eq(" + (i + 1) + ")").append($("<td></td>").text($(sorted2[i]).text()));
$("tr:eq(" + (i + 1) + ")").append($("<td></td>").text($(sorted3[i]).text()));
}
});
Your toggle code looks OK. When I have had a situation where it takes a second click to get the event to fire, it has been the case that I have applied the toggle twice to the selector (in this case firstRow). Or that there is more than one jQuery object.
Check that you have not applied it twice, or attach your code to a simple div to test if it is working independently of the firstRow selector. eg:
We may need to see your HTML too.