Quantcast
Viewing all articles
Browse latest Browse all 9

Set age based on date of birth

I had a requirement to set an ‘Age’ attribute based on the contents of the Date of Birth field on Contacts. The below script in the On Save, On Load or On Change will do this.

Note: You will need to change the “birthdate” and “new_age” field names to the relavant fields on your form.

CRM 2011

function calcBirthday() {
if(Xrm.Page.getAttribute("birthdate").getValue() != null)
{
var now = new Date(); //get today's date
var birthday = Xrm.Page.getAttribute("birthdate").getValue(); //get the dob value
var diff = now.getMonth() - birthday.getMonth();  //have they had their birthday already this year?
var age; //use to store age

if (diff == 0) //if birthday is this month, compare the days instead
{
diff = now.getDate() - birthday.getDate();
}

if(diff > -1) //if they've had a birthday this year
{
age = now.getFullYear() - birthday.getFullYear();
}
else //if they have not had a birthday yet this year
{
age = now.getFullYear() - birthday.getFullYear() - 1;
}

Xrm.Page.getAttribute("new_age").setValue(age.toString()); //set the new_age attribute
}
}

CRM 4

function calcBirthday(){
if(crmForm.all.birthdate.DataValue != null)
{
var now = new Date(); //get today's date
var birthday = crmForm.all.birthdate.DataValue; //get the dob value
var diff = now.getMonth() - birthday.getMonth();  //have they had their birthday already this year?
if (diff == 0) //if birthday is this month, compare the days instead
{
diff = now.getDate() - birthday.getDate();
}

if(diff > -1) //if they've had a birthday this year
{
var bd1 = now.getFullYear() - birthday.getFullYear();
crmForm.all.new_age.DataValue =bd1.toString(); //set the new_age attribute
}
else //if they have not had a birthday yet this year
{
var bd2 = now.getFullYear() - birthday.getFullYear() - 1;
crmForm.all.new_age.DataValue =bd2.toString();
}
}
}


Image may be NSFW.
Clik here to view.
Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 9

Trending Articles