JS to calculate Age of Contact
1. Create custom field 'Age' in whole number format, and then put it in the form. Remember the schema name of this field + lock the field in form.
2. Web Resource Type: Javascript
function CalculateAge(birthday, ondate) {
// if ondate is not specified consider today's date
if (ondate == null) { ondate = new Date(); }
// if the supplied date is before the birthday returns 0
if (ondate < birthday) { return 0; }
var age = ondate.getFullYear() - birthday.getFullYear();
if (birthday.getMonth() > ondate.getMonth() || (birthday.getMonth() == ondate.getMonth() && birthday.getDate() > ondate.getDate())) { age--; }
return age;
}
function birthdateOnChange() {
// read the birthday value from the birthdate field
var birthday = Xrm.Page.getAttribute("birthdate").getValue();
// if the date contains a value calculate the age
if (birthday != null) {
// get the age
var age = CalculateAge(birthday);
// set the age to the new_age field
Xrm.Page.getAttribute("new_age").setValue(age);
}
}
Replace the 2 schema names in the code with yours.
3. Add the Web Resource to Form Libraries, then to the Event Handlers and call function "birthdateOnChange"
4. In the Form, double click the DOB field and in the event tab under Event Handlers, press add and then select library and call this function "birthdateOnChange".
5. Save and publish the entity.
6. Enter data or change data in DOB | if data already there then on form onload you will see the correct Age!