This script allows you to ask for a participant's date of birth in a Date question, and then save their calculated age value in a hidden Number question.
Note: The age is static and captured at the time the script executes; it won't change over time. Age is calculated based on the first day of the provided month and year.
Detailed Steps
- In your survey, add a Page element.
- Add a Date question to the Page element.
Set the minimum and maximum values for the years (for example, 1920 and 2005). - Add a second Page element.
- Add a Number question to the second Page element.
You may want to leave this question unhidden for testing. - Open the first Page element for editing and click the Scripting button.
- Copy and paste the script below into the On Complete tab.
- Replace DateOfBirth with the name of the Date question.
- Replace Age with the name of the Number question.
- Click Save.
- Preview and test your survey.
Script
/*
Script Name: How do I calculate age based on a participant's Date of Birth response? (Modern Surveys)
To ensure your script works as expected, always copy the original script
from the Script Library found in the Alida Help Center. Failure to use the latest script
from the script library may cause unexpected results.
*/
const age = response.getDataPoint("Age");
const date = response.getDataPoint("DateOfBirth").get();
// Calculate age
var diff_ms = Date.now() - date.getTime();
var age_dt = new Date(diff_ms);
var age_r = age_dt.getFullYear() - 1970;
//Add validation in case the date is in the future
if(age_r < 0)response.setError("DateOfBirth","Please do not enter a date in the future.");
//Save result into date question and numeric
age.set(age_r);
Example
Sample survey structure:
Date of Birth Date question on the first page:
Calculated age in hidden Number question:
Comments
0 comments
Article is closed for comments.