java_newbie java_newbie - 7 months ago 44
Javascript Question

Jquery: get birthday value from page and substitute with age value

I have a

jsp
having a table with users info and there's a column representing user's birthday in format
yyyy-mm-dd
. I want to substitute those birth dates with actual age of user.
So I have simple JS function getAge for it:

function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}


I've tried to run it after page initializing in that way:

$().ready(function({
$(".age").html(getAge($(this).html()));
}));


where
.age
is a class of "Age" column. So that's the way I expected it to work:

$(".age")
- finds cell with class="age"

$(".age").html(getAge($(this).html()));
- substitues html in found cell with value returned from getAge() function where argument for getAge is current value in that cell.
but it shows nothing =(

If I use smthg like this for testing:

$(".age").html(getAge("1960-08-15"));
- it works correctly and substitutes birthdays in all rows with age calculated from 1960-08-15 =)

maybe I don't understand what
$(this)
returns in my context? I was sure it should return current element which I just invoked with my selector (cell)

Could you give me a hint?

thx a lot

Answer

You should loop through each age and set their html using jquery .each

$(".age").each(function(){....});

FIDDLE: http://jsfiddle.net/Yyene/