Jquery toggle functions

Posted by ozsenegal on Stack Overflow See other posts from Stack Overflow or by ozsenegal
Published on 2010-04-05T14:39:00Z Indexed on 2010/04/05 14:43 UTC
Read the original article Hit count: 299

Filed under:
|
|

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()));

        }
    });

© Stack Overflow or respective owner

Related posts about toggle

Related posts about jQuery