JavaScript to breakup date of birth for doing an age calculation | XM Community

JavaScript to breakup date of birth for doing an age calculation


Userlevel 7
Badge +6
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?

28 replies

Userlevel 2

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?

Userlevel 7
Badge +21

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()

Userlevel 2

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