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

JavaScript to breakup date of birth for doing an age calculation



Show first post

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