Skip to content

Instantly share code, notes, and snippets.

@alex-authlab
Last active January 8, 2023 22:27
Show Gist options
  • Save alex-authlab/cba0340b517362bc428d4a918d8ce699 to your computer and use it in GitHub Desktop.
Save alex-authlab/cba0340b517362bc428d4a918d8ce699 to your computer and use it in GitHub Desktop.
Birthday Calculation in Fluent Form
// Age calculator
// 1. First take a Date picker & a text input field
// 2. In the text input element add the class 'age'
// 3. Add a custom class 'date' in the date picker ,then add the following js in your fluent form custom js
jQuery( ".date" ).change(function() {
var age = getAge(jQuery(this).val())
jQuery('.age').val( age)
});
function getAge(DOB) {
//when date format dd/mm/yyyy
birthDate = DOB.split("/");
currentDate = new Date();
// javascript month counts from 0, so add +1
var years = (currentDate.getFullYear() - birthDate[2]);
if (currentDate.getMonth()+1 < parseInt(birthDate[1]) || currentDate.getMonth()+1 == parseInt(birthDate[1]) && currentDate.getDate() < birthDate[0]) {
years--;
}
if(years < 0){
years = 0;
}
return years;
}
@Benspy22
Copy link

Benspy22 commented Sep 5, 2022

Hello to all,
I am trying to transform a birth date into an age.

However, when I do the manipulation, it does not work (I use WP in French, but when I switch the site to English, it does not work either)
Can someone help me?
Thanks in advance

@Dimensionone
Copy link

Hi, there is an error in this script. The correct version that works for me is this one:

// Age calculator

// 1. First take a Date picker & a text input field 
// 2. In the text input element add the class 'age'
// 3. Add a custom class 'date' in the date picker ,then add the following js in your fluent form custom js


jQuery( ".date" ).change(function() {
    
    var age = getAge(jQuery(this).val())
    jQuery('.age').val( age).change();

});


function getAge(DOB) {
    
    //when date format dd/mm/yyyy
    birthDate = DOB.split("/");
    currentDate = new Date();
    
    // javascript month counts from 0, so add +1        
    var years = (currentDate.getFullYear() - birthDate[2]);
  
    if (currentDate.getMonth()+1 < parseInt(birthDate[1]) || currentDate.getMonth()+1 == parseInt(birthDate[1]) && currentDate.getDate() < birthDate[0]) {
        years--;
    }
    if(years < 0){
        years = 0;
    }
    return years;
}

@Niraj-ojha
Copy link

Its showing NaN in text box....any idea why ???

@Niraj-ojha
Copy link

and also, var age = getAge(jQuery(this).val()) it's showing semi column missing at this line

@star26bsd
Copy link

You may want to check line 21 whether you split by the right character, depending on the date format chosen. I had dots, so I had to adjust it to birthDate = DOB.split(".");

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment