Check out the LimeSurvey source code on GitHub!

calculate age from birthdate in CPDB token as answer to hidden question

3 years 5 months ago #99834 by seancon1
we import the participants birthday to the Central Participants Database, we want to add the age to the answers so we can create reports against the age...

i have created this javascript and it works correctly until i try to add the token as a variable
<script type="text/javascript" charset="utf-8">
   $(document).ready(function() {
    function calculateAge(birthDate) {
    birthDate = new Date(birthDate);
    var otherDate = new Date();
    var years = (otherDate.getFullYear() - birthDate.getFullYear());
    if (otherDate.getMonth() < birthDate.getMonth() || otherDate.getMonth() == 
           birthDate.getMonth() && otherDate.getDate() < birthDate.getDate()) {
    return years;
var dob = '{TOKEN:ATTRIBUTE_CPDB_2}';                      
var age = calculateAge(dob);
//  document.getElementById('q1124').value= age;

above i have it modified to alert the age but the commented line is the desired result.

i do not get an alert unless i swap the token for an actual date '11/01/1970' then the alert shows the age.

if i look at the source i see this
var dob = '<span style='background-color: #eee8aa;'><span title='Undefined variable' style='border-style: solid; border-width: 2px; border-color: red;'><span title='Undefined variable' style='color: red; font-weight: bold'>TOKEN:ATTRIBUTE_CPDB_2</span></span></span>';     

not sure what i am doing wrong here


Please Log in to join the conversation.

3 years 5 months ago #99845 by seancon1
this was supposed to be in the Can i do this with limesurvey? section.

Please Log in to join the conversation.

3 years 5 months ago #99869 by seancon1
i was able to fix the alert by changing
var dob = '{TOKEN:ATTRIBUTE_CPDB_2}';

var dob = "{TOKEN:ATTRIBUTE_CPDB_2}";

i get the correct age in the alert now.

to complete this i would like to change the alert

to enter the age as a default answer to the question.

is this done in the java code or by inserting a variable in the default answer field?

i have tried the following
$('#answer464957X16X491 input.text').val(age);


as well as {age} as a default answer

none of the above worked

how can i accomplish this?


Please Log in to join the conversation.

3 years 5 months ago #99875 by Ben_V
After double checking SGQA code ;) maybe try :
document.getElementById("#answer464957X16X491").value = (age);

BTW, I suppose you can be interested in this old post


EM Variables => | EM Roadmap =>
Last Releases => 2.6x.x | 2.06/2.6.x =>
Demo Surveys => (already included in /docs/demosurveys)

Please Log in to join the conversation.

Imprint                   Privacy policy         General Terms & Conditions         Revocation information and revocation form