Calculating age from date field to dynamically populate hidden field

I’m hoping someone can help me with this. I have a form where I gather dates of birth. If someone is above the age of 55, I want to ask them additional questions. I’m trying to cobble together the code to calculate the age based on date of birth and then dynamically populate a hidden “yes or no” radio button field that will then trigger the additional questions through conditional logic. Thanks in advance–Brad

There is no great, built in way to do this. You will be cobbling something together. Some pieces that may help:

That is normally used to calculate the number of days between two datepickers. You could have a hidden datepicker populated with today’s date. Next would be the Date of Birth datepicker. When the user selects their date of birth, this code would calculate the number of days. 55 years would be around 20,075 days (not accounting for extra days in a leap year, which would change from today to tomorrow and further years into the future. For example, it’s 20,088 since your birthday 55 years ago on Sept 15, 2019.) Now, you can base conditional logic on that calculated field that says “show this section with additional questions when the number of days is greater than 20075”.

The other way to do it would be to use the gform_validation filter to calculate the number of days since the date of birth given on page one of a multi-page form. Then, you can populate a field that you would use for conditional logic on page two of the multi-page form to show or hide the additional questions. If you have a lot of questions, the multi-page form would work well, especially if page two has other questions on it, not just ones that pertain if you are over 55 years old.

1 Like

I think the easiest way would be to just enqueue some javascript with the form. Add a className to the date field you can target with event listener onChange and then calculate the age from the value of the field. From there you can target the className on the radio button to set it to yes/no based on the age. Below is a function to help you calculate the date.

Hope this helps.

function get_age_from_birthday(birthday) 
  var today = new Date(),
    birth_date = new Date(birthday),
    age = today.getFullYear() - birth_date.getFullYear(),
    m = today.getMonth() - birth_date.getMonth();

  if (m < 0 || (m === 0 && today.getDate() < birth_date.getDate())) 

  return age;
1 Like