Forums

Calculate Age from Date of Birth

arrick 29 Apr, 2015
Good Morning,

I would like to have the field "appAge" be auto-calculated based on the date given in "appDOB" which has a mask of mm/dd/yyyy. I could use some help getting it to format

You can preview the form located at http://mwforms.miworksmo.org/wiareg.

I would like to know the best course of action to take with this, as I have been able to calculate the appropriate age with a simple PHP page, which the code looks like this for:


<?php
/**
 * Simple PHP age Calculator
 * 
 * Calculate and returns age based on the date provided by the user.
 * @param   date of birth('Format:mm-dd-yyyy').
 * @return  age based on date of birth
 */
function ageCalculator($dob){
	if(!empty($dob)){
		$birthdate = new DateTime($dob);
		$today   = new DateTime('today');
		$age = $birthdate->diff($today)->y;
		return $age;
	}else{
		return 0;
	}
}
$dob = '1975-12-22';
echo ageCalculator($dob);
?>


Because I am still learning this on the fly, I could use some help and recommendations...

Thank You.
GreyHead 29 Apr, 2015
Hi moorear,

I'm not clear - do you want to do this using JavaScript while the form is displayed? If so please see this StackOverFlow answer

In PHP after the form submits your code looks fine.

Bob
arrick 29 Apr, 2015
I would like the field to be set as soon as the appDOB changes, so that I can enable/disable other fields based on the age of the job seeker.

I am unsure how to put this into the form, where to put it, etc...
GreyHead 05 May, 2015
Hi moorear,

I just tested this and it seems to work OK. the getAge function is take exactly from the link I posted earlier. Here i have two inputs a datepicker with the id='appDOB' and a text input with the id='age'. You should probably set the age input to be readonly, and the datepicker to start in year view and block future dates.
jQuery(document).ready(function(jQ){
  jQ('#appDOB').on('change', function() {
    var age, dob;
    dob = jQ('#appDOB').val();
    age = getAge(dob);
    jQ('#age').val(age);
  });

  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;
}
});

Bob
ilsroma 04 Apr, 2016
Hi GreyHead,
I try to insert this script but it doesn't work😟 the text area "AGE" says Nan. why?
GreyHead 04 Apr, 2016
Hi ilsroma,

What is the format of the dates in your form? I suspect that may be the problem here as the script worked in my tests

Bob
This topic is locked and no more replies can be posted.