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

JavaScript

How 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

Something 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)

its saying changeDate is undefined :(

Maybe try to put it into quotes? So you will have the following:

$('.datepicker').datepicker().on("changeDate", function(e) {

i 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

,,, $('#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); });;  ,,,

obviously im un aware of how to paste code snippets....