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