JavaScript to breakup date of birth for doing an age calculation | XM Community
Skip to main content
I am trying to record age at the time of taking the survey, using a an embedded data (Date of birth) in the format YYY-MM-dd. Because date of birth is in 1 embedded field, and not 3 (year of birth, month of birth, day of birth) I can't do an age calculation in survey flow (which is fine as the logic for this is a bit messy and I have a lot of surveys I'd need to add this to).



I imagine javascript code could be written that will calculate the age based on the date if birth field I have, but I am not sure how to write it. Can anyone help?

I'm jumping onto this conversation late, but it's relevant to my current problem.
I ask date of birth in a field of a multi-field text entry form and want to computer the person's age.
I got the JS code to work correctly when the date of birth is a stand-alone field.
Qualtrics.SurveyEngine.addOnPageSubmit(function() 
{
  var age = moment().diff(moment(jQuery("#"+this.questionId+" .InputText").val()), 'years');
  Qualtrics.SurveyEngine.setEmbeddedData('UserAge', age);
});
But, when I tried to adapt this code to a multi-field form.
Qualtrics.SurveyEngine.addOnPageSubmit(function() 
{
  var age = moment().diff(moment(jQuery("${q://QID4/ChoiceTextEntryValue/5}").val()), 'years');
  Qualtrics.SurveyEngine.setEmbeddedData('UserAge', age);
});

I get UserAge = 0 regardless of the date of birth.

I'm assuming that the syntax I used to specify the field is incorrect.
Can you give me any suggestion of what I need to change?


Change:

jQuery("${q://QID4/ChoiceTextEntryValue/5}").val()

To:
"${q://QID4/ChoiceTextEntryValue/5}"

In the earlier code jQuery().val() was used to extract the text from the input box. Piped text will give it your directly. Also, if you are using it on the same question, then it will not work, because piping text requires a page break between input and use.
If you're using it in the same question, you will probably need something like:
jQuery("#"+this.questionId+" .InputText").eq(4).val()


This was very helpful.
I used your final suggestions (i.e., the "same question" approach).
It took me a bit to figure out what ".eq(4)" was for and that I needed to start counting from 0 and not 1.
But, it's working now, so all is good.
Thanks much.,


Leave a Reply