// Get the birthdate input
var birthdateInput = this.getQuestionInput('Q4'); // Replace 'Q4' with the actual Question ID of your birthdate question
// Calculate the age
var today = new Date();
var birthdate = new Date(birthdateInput);
var age = today.getFullYear() - birthdate.getFullYear();
var m = today.getMonth() - birthdate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthdate.getDate())) {
age--;
}
// Output the age
console.log(age); // You can replace 'console.log' with any other method of outputting the age, such as displaying it on the page or storing it in a hidden question
});
First, I would change the birthdate question to a calendar picker using the JavaScript found from Flatpickr.
Place in the Header:
https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet" />
Add JavaScript to the question:
Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/
jQuery("#"+this.questionId+" .InputText").flatpickr({
dateFormat: "d/m/Y"
});
I would then use moment.js to calculate the age.
Create Embedded data field:
Create "age" and set value to "x"
Place in the Header:
">https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js">
Add JavaScript to the question:
Qualtrics.SurveyEngine.addOnload(function() {
var bdate = moment("Add Birthday Question ID","MM/DD/YYYY");
Qualtrics.SurveyEngine.setEmbeddedData('age',moment().diff(bdate,'years'));
});
Last, Pipe Text the embedded data field "Age" into the age question.
Be sure there is a page break between Q3 & Q4
For the age calculation you’ll need to have the following in the header:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
For the date picker, you’ll need to have the following header:
<link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet" /><script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
To answer your question directly, your header should contain the following:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css" rel="stylesheet" /><script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
In the survey flow, place “Age” above the blocks with JavaScript.
Make sure there is a page break between the two Questions with JavaScript
Make sure that the capitalization for age is the same in both the JavaScript and survey flow.
Leave a Reply
Enter your E-mail address. We'll send you an e-mail with instructions to reset your password.