Pepe
Pepe

Reputation: 1002

Sort div values with "." instead of "," correctly?

I use the following script to sort div values, but the problem at this way of sorting is that it only works correctly with numbers if I use a "," instead of "." - is there any way to this with dots?

var $divs = $("div.box");

$('#alphBnt').on('click', function () {
    var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
        return $(a).find("h1").text() > $(b).find("h1").text();
    });
    $("#container").html(alphabeticallyOrderedDivs);
});

$('#numBnt').on('click', function () {
    var numericallyOrderedDivs = $divs.sort(function (a, b) {
        return $(a).find("h2").text() > $(b).find("h2").text();
    });
    $("#container").html(numericallyOrderedDivs);
});

At my fiddle you can see that the dates are not correctly sorted if you click on "#numBnt".

My fiddle

Upvotes: 2

Views: 102

Answers (2)

Rahul Desai
Rahul Desai

Reputation: 15501

You need to convert the text with dates into JS Date object like this:

new Date( $(a).find("h2").text() ).

Updated fiddle

JS:

var $divs = $("div.box");

$('#alphBnt').on('click', function () {
    var alphabeticallyOrderedDivs = $divs.sort(function (a, b) {
        return $(a).find("h1").text() > $(b).find("h1").text();
    });
    $("#container").html(alphabeticallyOrderedDivs);
});

$('#numBnt').on('click', function () {
    var numericallyOrderedDivs = $divs.sort(function (a, b) {
        // here is the change:
        return new Date($(a).find("h2").text()) - new Date($(b).find("h2").text());
    });
    $("#container").html(numericallyOrderedDivs);
});

Try playing around with different dates to test the fiddle.

Also go over this answer.


EDIT:

Fix for Firefox:

Firefox doesnt like . as the delimeter in dates. It needs to be replaced by /.

new Date($(a).find("h2").text().replace(/\./g, '/'))

Updated fiddle for Firefox.

Source

Upvotes: 1

Flash Thunder
Flash Thunder

Reputation: 12045

Use parseFloat($(a).find("h2").text().replace(",", ".")); for numbers...

And for dates...

(new Date($(a).find("h2").text())).getTime()

Upvotes: 0

Related Questions