Javascript to calculate user's age, based on DOB, check age eligibility, & provide validation alert | XM Community
Solved

Javascript to calculate user's age, based on DOB, check age eligibility, & provide validation alert


A major goal of our recruitment survey is to identify users who are between the ages of 14-24 (target population) and those who are not (not eligible for our study). Currently we ask users for their date of birth (MM/DD/YYYY) and would like to use JS to:

1. Calculate age, based on the current date
2. Determine if the age is within our target range (14-24)
3. Provide a validation alert to the users AND/OR categorize users using embedded data in the categories of eligible/ineligible based on age

Please take a look at the code I have now for the DOB question:

Qualtrics.SurveyEngine.addOnReady(function()
{
var dob_entry = getTextValue();
var split_dob = dob_entry.split("/");
var month = split_dob[0];
var day = split_dob[1];
var year = split_dob[2];
var dob_asdate = new Date(year, month, day);
var today = new Date();
var mili_dif = Math.abs(today.getTime() - dob_asdate.getTime());
var age = (mili_dif / (1000 * 3600 * 24 * 365.25));
within_age_range=(14<age & age<24);

alert(age);
});
icon

Best answer by MohammedAli_Rajapkar 25 July 2018, 18:36

View original

37 replies

Userlevel 2
Badge +2

Hi @MohammedAli_Rajapkar ,

 

How exactly do I add an embedded data?

Is my code below correct?
 

Qualtrics.SurveyEngine.addOnReady(function()
{
var current_date = "${date://CurrentDate/DS}";
    var year1 = current_date.substr(0, 4);
    var Qyear = "${q://QIDSQ_yearofbirth/ChoiceTextEntryValue}";
    var captureAge = parseInt(year1) - parseInt(Qyear);
    Qualtrics.SurveyEngine.setEmbeddedData('UserAge', captureAge);

});

This is a screenshot of my question in Qualtrics:

 

Badge

I have a similar situation as to what's shown in this thread, but (I think) the main difference is how were are gathering DOB. We are not using a calendar, but rather a matrix table that captures month, day and year fields separately.
image.pngThe existing Javascript for the matrix table is attached here.
DOB script.txt
I would like to have a similar formula that can calculate the age. Is this possible with the matrix table too? If so, what would that process look like?

Userlevel 7
Badge +27

https://www.qualtrics.com/community/discussion/comment/36777#Comment_36777My guess would be that the jsdelivr src in the header is wrong. In the message above the Qualtrics Community automatically replaced a string that contained an @ with [email_protected]. If that is the problem, go to jsdelivr search for moment.js. jsdeliver will create the correct

Hi TomG,
Could you please let me know how do I load moment.js in survey header. Because when I have load whole JS codes "Qualtrics.SurveyEngine.addOnPageSubmit(function() {  var age = moment().diff(moment(jQuery("#"+this.questionId+" .InputText").val()), 'years');  Qualtrics.SurveyEngine.setEmbeddedData('age', age);  if(age > 13 && age < 25) Qualtrics.SurveyEngine.setEmbeddedData('eligible', '1');});" in survey header. Then the whole code is appearing on the screen. And code is not running.

Please let me know if I have to load any specific code?
Regards,
Ashish

Userlevel 7
Badge +27
No. "this" is the current question object and "this.questionId" is the current question id (e.g. QID1").

Are you using single line text entry question?
Are you entering the date in a format moment can parse?

It might help if you post a preview link to your survey (or a block that contains your DOB question).
Hmm, I checked the header, and it's good. It's still not validating. Should I be replacing any of the JS with my own code, e.g. ("#"+this.questionId+" .InputText")? Inserting the questionID?
Userlevel 7
Badge +27
> @nkumich said:
> Thanks for simplifying the solution @TomG. I've read your's and others' threads on moment.js and I think I have it set up right, but I must be missing something. Do I need to assign an embedded data field labeled "age" (I don't know how to do this.
You don't need to do anything additional with "age" for it to work. However, if you want age saved in your response data, you need to initialize it in your survey flow before the block with the DOB question.

If it is not working, make sure you added the moment.js script to your survey header.
Thanks for simplifying the solution @TomG. I've read your's and others' threads on moment.js and I think I have it set up right, but I must be missing something. Do I need to assign an embedded data field labeled "age" (I don't know how to do this.

Here is what I've done so far, in the header:

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.21.0/moment.min.js"></script>

And this in the question JS field:

Qualtrics.SurveyEngine.addOnload(function()
{
/*Place your JavaScript here to run when the page loads*/

});
Qualtrics.SurveyEngine.addOnPageSubmit(function() {
var age = moment().diff(moment(jQuery("#"+this.questionId+" .InputText").val()), 'years');
Qualtrics.SurveyEngine.setEmbeddedData('age', age);
if(age > 13 && age < 25) Qualtrics.SurveyEngine.setEmbeddedData('eligible', '1');
});

Qualtrics.SurveyEngine.addOnUnload(function()
{
/*Place your JavaScript here to run when the page is unloaded*/

});

Thanks for your expertise!


> @TomG said:
> I don't remember seeing this question before @mjs5az resurrected it, but the answers given are doing it the hard way and the accepted answer isn't always accurate. You can do everything @nkumich asked for by using moment.js and adding this script to the DOB question:
> ```
> Qualtrics.SurveyEngine.addOnPageSubmit(function() {
> var age = moment().diff(moment(jQuery("#"+this.questionId+" .InputText").val()), 'years');
> Qualtrics.SurveyEngine.setEmbeddedData('age', age);
> if(age > 13 && age < 25) Qualtrics.SurveyEngine.setEmbeddedData('eligible', '1');
> });
> ```
> Demo survey
Hi, is there anyway this question can be done by Qualtrics? I am not familiar with JS. I tried to import the question from the library as in the first comment but then content validation is not available. Anyone know the easy way just to ask year born and qualifies age from there?
@TomG I've aded in a previous comments the code I've added in (1).

The issue is that when in (3) I choose:
(a) Branch if eligible is Not Equal to 1 then End of Survey = I'm out of the survey no matter my DOB (older or younger than 15)
(b) Branch if eligible is Equal to 1 then End of Survey = I'm not screened out of the survey, no matter my DOB (older or younger than 15)

So it looks like the Embedded data attributed is always "1", which I don't understand.
> @TomG said:
> > @annaj said:
> > @TomG Thanks for the hint! Could you please explain me how to use cleave.js? What piece of code should I add in the question?
> I've answered this before. Try this thread: https://www.qualtrics.com/community/discussion/comment/2682#Comment_2682
>

@TomG Many thanks! I will check this out!
Userlevel 7
Badge +27
> @annaj said:
> @TomG Thanks for the hint! Could you please explain me how to use cleave.js? What piece of code should I add in the question?
I've answered this before. Try this thread: https://www.qualtrics.com/community/discussion/comment/2682#Comment_2682
> @TomG said:
> > @annaj said:
> > @TomG Hi! I would be interesting as well in adding the "/" to assist wit the date format. Would it be possible to get your advice on this? Many thanks!
> Use cleave.js
>
>

@TomG Thanks for the hint! Could you please explain me how to use cleave.js? What piece of code should I add in the question?
Userlevel 7
Badge +27
> @annaj said:
> @TomG Hi! I would be interesting as well in adding the "/" to assist wit the date format. Would it be possible to get your advice on this? Many thanks!
Use cleave.js
@TomG Sorry here is the code in (1): !

Is that correct?
I can't understand why it doesn't work. Do I need to add any embedded data?
Userlevel 7
Badge +27
> @annaj said:
> Am I missing something?
You've got all the correct steps. Your code under (1) doesn't display, but if that is correct, it should work.
@TomG In addition, I tried to exclude participants to my survey based on their DOB. I want only people who are between 16 and 99.

1. I've added in Qualtrics header (in Look & Feel) this piece of code: <script type="text/javascript" data-runid="016570089713574543" src="https://cdn.jsdelivr.net/npm/moment@2/moment.min.js"></script>

2. I've added this piece of code in the DOB question:
Qualtrics.SurveyEngine.addOnPageSubmit(function() {
var age = moment().diff(moment(jQuery("#"+this.questionId+" .InputText").val()), 'years');
Qualtrics.SurveyEngine.setEmbeddedData('age', age);
if(age > 15 && age < 100) Qualtrics.SurveyEngine.setEmbeddedData('eligible', '1');
});

3. In the Survey Flow, I've added this:
Branch if eligible is Not Equal to 1 then End of Survey

Am I missing something?

Many thanks for your support!
Best,
Anais
> @TomG said:
> > @mjs5zx said:
> > @TomG This works. Thanks so much. Also, I really like how your demo survey automatically adds the '/' to assist with the date format. Would you be willing to help me learn how to do that?
>
> @mjs5zx - I'll send you a message.

@TomG Hi! I would be interesting as well in adding the "/" to assist wit the date format. Would it be possible to get your advice on this? Many thanks!

Leave a Reply