Submit a ticket Agent Login
Welcome
Login  Sign up

Set Age from DOB Question

You can use JavaScript to set the numeric age in a hidden question after you have asked the Date of Birth question.


This code below relies on you piping through the answer from the previous question:





function pageReady() {  
    // Get DOB string from hidden cRef element  
    var dobStr = $(".cRef").eq(0).text().trim();
  
    if (!dobStr) return;
  // Expecting dd/mm/yyyy  
    var parts = dobStr.split("/");  

    if (parts.length !== 3) return;
      
    var day   = parseInt(parts[0], 10);  
    var month = parseInt(parts[1], 10) - 1; 
    // JS months are 0-based  
    var year  = parseInt(parts[2], 10);

    if (isNaN(day) || isNaN(month) || isNaN(year)) return;
  
    var dob   = new Date(year, month, day);  
    var today = new Date();
    var age = today.getFullYear() - dob.getFullYear();
    var monthDiff = today.getMonth() - dob.getMonth();
    var dayDiff = today.getDate() - dob.getDate();
  
    // Adjust if birthday hasn't occurred yet this year
    if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {age--;}
    // Safety check  
    if (age < 0 || age > 120) return;
    // DCv2: numeric fields use .numeric-decimal-input, fire 'input' event  
    $(".numeric-decimal-input").eq(0).val(age).trigger("input");
    $(".main-next-button").click();  
    $(".main-back-button").hide();
}






Did you find it helpful? Yes No

Send feedback
Sorry we couldn't be helpful. Help us improve this article with your feedback.