How can I calculate age based on the year selected? I need javascript to do this. | XM Community
Skip to main content

Here is the question for your reference. All I need to do is calculate the Age of the Respondent based on the current year.

Hi there, I found a thread that I think might be helpful to you.
https://community.qualtrics.com/XMcommunity/discussion/1397/javascript-to-calculate-users-age-based-on-dob-check-age-eligibility-provide-validation-alert
In that, TomG provides a solution on how to do what you are describing.
In your survey Header over in the Look & Feel, input the below code:


Then, within the Text Entry question of your survey that collects the Birthdate, add the below JS at the bottom, after the OnUnload:
Qualtrics.SurveyEngine.addOnPageSubmit(function()
{
  var age = moment().diff(moment(jQuery("#"+this.questionId+" .InputText").val()), 'years');
  Qualtrics.SurveyEngine.setEmbeddedData('age', age);
});
Just make sure that the Birthdate is in a format that moment.js can parse.


Leave a Reply