This topic is locked

Calculate age based on date of birth

3/13/2021 2:46:13 PM
PHPRunner Tips and Tricks
admin

A popular question, how to calculate the age based on the selected birth date. In this example, we do this in real-time using Javascript calculation added to the 'editing' field event of DateOfBirth field.


Proceed to Page Designer, double-click on DateOfBirth field, and add a field event for 'editing'. The following code goes to ClientBefore part of the event. Server and ClientAfter parts can be left empty. If your age field name is not Age, change it in the code accordingly. Now you can select the birth date and see Age field updated automatically.

var birthDate = new Date(ctrl.getValue())

var today = new Date();
var age = today.getFullYear() - birthDate.getFullYear();

var m = today.getMonth() - birthDate.getMonth();

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

age--;

}
Runner.getControl(pageid,'Age').setValue(age);