2

I have a datepicker function that's supposed to check if the user above 18 or not. If not then a prompter will appear.

This is what I have now but it's not working as how I want it to - I am getting the user's age correctly but not by month but by year which is not accurate:

$(document).ready (function () {
$('#dob2').datepicker();
$('#dob2').datepicker ("option", "changeMonth", true);
$('#dob2').datepicker ("option", "changeYear", true);
$('#dob2').datepicker ("option", "yearRange", "-100:-16");
$('#dob2').datepicker ("option", "maxDate", "-16Y");
$('#dob2').datepicker ("option", "minDate", "-100Y");
$('#dob2').datepicker ("option", "minDate", "-100Y");
$('#dob2').datepicker ("option", "onSelect", function(dateText, inst) { 
            var date = $(this).datepicker('getDate');
            var year  = date.getFullYear();  
            var curYear = new Date().getFullYear();
            age = curYear - year;
            console.log(age);
            if(age>=16 || age<18){
                alert("The minimum age requirement for supplementary card applicant is 18 years old. For applicant aged 16 and 17, and are going overseas to study, please submit the letter of acceptance from the education institution.");
            }
       });

   });

What I want it to do is to have the Prompter to be shown for those who aged 16 & 17, should also be prompted to those who are turning 18 but yet to pass their birth date as technically they are still 17 y.o.

rory-h
  • 660
  • 1
  • 12
  • 30

2 Answers2

2

Try this.

$('#dob2').datepicker("option", "onSelect", function(dateText, inst) {
    var dob = $(this).datepicker('getDate');
    var age = GetAge(dob);
    if (age >= 16 && age < 18) {
        alert("The minimum age requirement for supplementary card applicant is 18 years old. For applicant aged 16 and 17, and are going overseas to study, please submit the letter of acceptance from the education institution.");
    }
});

function GetAge(birthDate) {
    var today = new Date();
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
naveen
  • 53,448
  • 46
  • 161
  • 251
0

Works for me

    $("#FechaNacimientoDate").change(function () {
        var today = new Date();
        var birthDate = new Date($(this).datepicker('getDate'));
        var age = today.getFullYear() - birthDate.getFullYear();
        var m = today.getMonth() - birthDate.getMonth();
        if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
            age--;
        }

        return $('#Edad').val(age);
    });