I'm working on a survey where I ask parents for their baby's birthdate and then want to display different questions based on their baby's age in months. I read many threads regarding this issue but still didn't manage to make this thing work.
Here is what I've done so far:
1. create this survey flow with an empty 'age' embedded data at the beginning of the survey:
2. Add these scripts to the header of the survey:
3. Add this code to the DOB question to create a Flatpick question that supposes to calculate the age in months and then insert it into the embedded data:
jQuery("#"+this.questionId+" .InputText").flatpickr({enableTime: false, altInput: true, altFormat: "d/m/Y ", dateFormat: "d/m/Y ", time_24hr: false});
var age = moment().diff(moment(jQuery("#"+this.questionId+" .InputText").val()), 'months');
Qualtrics.SurveyEngine.setEmbeddedData('age', age);
4. Add display logic to the last question.
But from what I see, the code just doesn't work. The embedded data stays empty no matter what I enter to the DOB question.
You can see this demo survey live here:
https://bgu.qualtrics.com/jfe/form/SV_3fs4Rf5i60XkNg2
What am I missing?
Thank you
Two issues:
- Your age calculation needs to be in the addOnPageSubmit() function
- You need to have moment parse the correct input date format
You should really use the Moment replacement Luxon.
Thank you Tom,
Using your advice (and after spending some time with chat GTP), I managed to make it work. This is the final code for other people who struggle with JavaScript:
/*for the flatpickr field*/
Qualtrics.SurveyEngine.addOnload(function()
{
jQuery("#"+this.questionId+" .InputText").flatpickr({enableTime: false, altInput: true, altFormat: "d/m/Y ", dateFormat: "d/m/Y ", time_24hr: false});
});
/*for calculation and store the age field*/
Qualtrics.SurveyEngine.addOnPageSubmit(function(type) {
/* Place your JavaScript here to run when the page is submitted */
var dob = moment(jQuery("#"+this.questionId+" .InputText").val(), "DD/MM/YYYY");
var age = moment().diff(dob, 'months');
Qualtrics.SurveyEngine.setEmbeddedData('age', age);
});
Most people probably want the age in years, so you just need to change "months" to "years" here:
var age = moment().diff(dob, 'years');
https://community.qualtrics.com/XMcommunity/discussion/comment/55576#Comment_55576Since I gave the correct answer, you should accept it.
Leave a Reply
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.