Reputation: 1002
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".
Upvotes: 2
Views: 102
Reputation: 15501
You need to convert the text with dates into JS Date
object like this:
new Date( $(a).find("h2").text() )
.
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.
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, '/'))
Upvotes: 1
Reputation: 12045
Use parseFloat($(a).find("h2").text().replace(",", "."));
for numbers...
And for dates...
(new Date($(a).find("h2").text())).getTime()
Upvotes: 0