0

Here's the jsFiddle.

As you can see from the fiddle, the total column contains numbers that are currently sorted by text.

Q: How can I sort the total column by the numerical value?

var table = $('table');

    $('#facility_header, #city_header, #total')
        .wrapInner('<span title="sort this column"/>')
        .each(function(){

            var th = $(this),
                thIndex = th.index(),
                inverse = false;

            th.click(function(){

                table.find('td').filter(function(){

                    return $(this).index() === thIndex;

                }).sortElements(function(a, b){

                    return $.text([a]) > $.text([b]) ?
                        inverse ? -1 : 1
                        : inverse ? 1 : -1;

                }, function(){

                    // parentNode is the element we want to move
                    return this.parentNode; 

                });

                inverse = !inverse;

            });

        });

1 Answer 1

2

You have to parse the values before you compare them.

.sortElements(function(a, b){
    var sa = $.text([a]);
    var sb = $.text([b]);

    var ia = parseInt(sa);
    var ib = parseInt(sb);

    if (!isNaN(ia) && !isNaN(ib)) {
        return ia > ib ? (inverse ? -1 : 1) : (inverse ? 1 : -1);
    }

    return sa > sb ? (inverse ? -1 : 1) : (inverse ? 1 : -1);
}

Here's your updated jsfiddle.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.