Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Alexander Foster
4,725 PointsHow would i calculate a users age based on the date they picked from boot-strap datepicker
hello fellow web enthusiasts, i am currently working on a project for a client and one of the tasks i am to complete is calculating a users age based on the date they picked from the calendar. i am using bootsrap-datepicker as my calendar. What i want to achieve is when a user picks a date from the calendar it replaces the <span class="calculate-age"></span> text with the users age based on the date they have picked. i have looked on stack and many other sites but nothing seems to be working out. Any suggestions?
3 Answers
Torben Ewert
3,172 PointsSomething like this should work:
$('.datepicker').datepicker().on(changeDate, function(e) {
var currentDate = new Date();
var selectedDate = new Date(e.date.toString());
var age = currentDate.getFullYear() - selectedDate.getFullYear();
var m = currentDate.getMonth() - selectedDate.getMonth();
if (m < 0 || (m === 0 && currentDate.getDate() < selectedDate.getDate())) {
age--;
}
$('.datepicker').val(age);
});
(I didn't test it)
Alexander Foster
4,725 Pointsi had to change var selectedDate = new Date($(this).val()); and the last line i needed to change class to .calculate-age and use html instead of val
Alexander Foster
4,725 Points,,, $('#cal').datepicker().on('change', function(e) {
var currentDate = new Date();
var selectedDate = new Date($(this).val());
var age = currentDate.getFullYear() - selectedDate.getFullYear();
var m = currentDate.getMonth() - selectedDate.getMonth();
if (m < 0 || (m === 0 && currentDate.getDate() < selectedDate.getDate())) {
age--;
}
$('#calculate-age').html(age); });; ,,,
Alexander Foster
4,725 Pointsobviously im un aware of how to paste code snippets....
Alexander Foster
4,725 PointsAlexander Foster
4,725 Pointsits saying changeDate is undefined :(
Torben Ewert
3,172 PointsTorben Ewert
3,172 PointsMaybe try to put it into quotes? So you will have the following:
$('.datepicker').datepicker().on("changeDate", function(e) {