Hi everyone,
I am not very tech-inclined and have little experience with JavaScript (or programming languages, for that matter), so please go easy on me. I have seen similar questions in the community but have found them hard to follow or not applicable (e.g., calculating in years).
I am looking to group my participants in three different ways: A) under 18 months, B) 18 - 30 months, and C) 30+ months. At the moment, I ask their parent to input their child's age in months and use that number to branch off of, but this can lead to parents miscalculating their child's age in months. I would prefer for the survey to automatically calculate it for them after they enter the child's date of birth.
Any help would be appreciated. Thank you!
Solved
Calculate Age (in months) from Date of Birth?
Best answer by TomG
JonesE wrote:
Ok, so now I’m trying a different approach (suggested by
Qualtrics.SurveyEngine.addOnPageSubmit(function()
{
var age = moment().diff(moment(jQuery("#"+this.questionId+" .InputText").val()), 'months');
Qualtrics.SurveyEngine.setEmbeddedData('age', age);
});
Any suggestions on what I’m doing wrong?
This is the better approach. I’m not sure if it is the only issue, but you didn’t provide a format to parse the date.
Moment has been replaced by Luxon, so it would be better to use that:
Survey header:
<script src="https://cdn.jsdelivr.net/npm/luxon@3/build/global/luxon.min.js"></script>
Age question JS:
Qualtrics.SurveyEngine.addOnPageSubmit(function() {
var DateTime = luxon.DateTime;
var birthDate = DateTime.fromFormat(jQuery("#"+this.questionId+" .InputText").val(),"MM/dd/yyyy");
var age = DateTime.now().diff(birthDate, ['months','days']).toObject();
Qualtrics.SurveyEngine.setEmbeddedData('age',age.months);
});
Leave a Reply
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.