Category Archives: Javascript

Getting the current age from a form using javascript

How to get the current age of a user from a form where the input is from:

1. Select list (Birth month) – return value of month (e.g. “January”)

2. Select list (Birth date)- return value of 1-31

3. Select list (Birth year) – return value of year (e.g. 2016)

 

 

   
      function getAge(birth_month, birth_day, birth_year){
        switch(birth_month){
            case "January": 
                birth_month = 0;
                break;
            case "February": 
                birth_month = 1;
                break;
            case "March": 
                birth_month = 2;
                break;
            case "April": 
                birth_month = 3;
                break;
            case "May": 
                birth_month = 4;
                break;
            case "June": 
                birth_month = 5;
                break;
            case "July": 
                birth_month = 6;
                break;
            case "August": 
                birth_month = 7;
                break;
            case "September": 
                birth_month = 8;
                break;
            case "October": 
                birth_month = 9;
                break;
            case "November": 
                birth_month = 10;
                break;
            default:
                birth_month = 11;
        }
        
        today_date = new Date();
        today_year = today_date.getFullYear();
        today_month = today_date.getMonth();
        today_day = today_date.getDate();
        age = today_year - birth_year;

        if ( today_month < (birth_month - 1)){
            age--;
        }
        if (((birth_month - 1) == today_month) && (today_day < birth_day)){
            age--;
        }
        return age;
    }