I am trying to display numbers within a particular table with ordinal suffixes. The table always shows three numbers which come from an XML file. The numbers show ranks, so for
It's not working because you're returning the strings to $.each
, not actually using them. Usage would depend on your HTML but here is an example of setting the .ordinal
text to the value.
You were also missing the i
parameter on the event handler and you can increment i
to start from 1st
instead of 0th
.
jsFiddle
$(".ordinal").each(function (i) {
i++;
var j = i % 10,
str;
if (j == 1 && i != 11) {
str = i + "st";
} else if (j == 2 && i != 12) {
str = i + "nd";
} else if (j == 3 && i != 13) {
str = i + "rd";
} else {
str = i + "th";
}
$(this).text(str);
});
If you have the numbers in your elements already then it would be best to not rely on the index and instead check the number, then append the string to the end.
jsFiddle
$(document).ready(function () {
$(".ordinal").each(function (i) {
var j = parseInt($('ordinal').text(), 10) % 10,
str;
if (j == 1 && i != 11) {
str = "st";
} else if (j == 2 && i != 12) {
str = "nd";
} else if (j == 3 && i != 13) {
str = "rd";
} else {
str = "th";
}
var elem = $(this)
elem.text(elem.text() + str);
});
});
This is what I use, and it works for any year, month, day (leap year) included:
// panelyear, panelmonth and panelday are passed as parameters
var PY01 = parseInt(panelyear); var PM01 = (parseInt(panelmonth) - 1); PD01 = parseInt(panelday);
var now = new Date(PY01, PM01, PD01);
var start = new Date(PY01, 0, 0);
var diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
var oneDay = 1000 * 60 * 60 * 24;
var day = Math.floor(diff / oneDay);
function getNumberWithOrdinal(n) { var s = ["th","st","nd","rd"], v = n % 100; return n + (s[(v - 20) % 10] || s[v] || s[0]); }
Use with
<script> document.write(getNumberWithOrdinal(day)); </script>