Welcome to the nuBuilder Forums!

Register and log in to access exclusive forums and content available only to registered users.

Calculate the age Topic is solved

Questions related to customising nuBuilder Forte with JavaScript or PHP.
Post Reply
yvesf
Posts: 315
Joined: Sun Mar 14, 2021 8:48 am
Location: Geneva
Has thanked: 87 times
Been thanked: 11 times

Calculate the age

Unread post by yvesf »

Hello,


I have date of birth and I would like to calculate the age in a calc field. Is it possible ? I have tried with the following script :

Code: Select all

function ageCalc(birth,age_num) {
let o = $('#' + birth);
let d = nuFORM.removeFormatting(o.val(), o.attr('data-nu-format'));
 var dob = new Date(d);  
    //calculate month difference from current date in time  
    var month_diff = Date.now() - dob.getTime();  
      
    //convert the calculated difference in date format  
    var age_dt = new Date(month_diff);   
      
    //extract year from date      
    var year = age_dt.getUTCFullYear();  
      
    //now calculate the age of the user  
    var age = Math.abs(year - 1970);  
console.log('age='+age);
nuSetvalue('age_num',age); 

} 
I have 2 fields pa_birthdate (date field with format yyyy-mm-dd) and pa_age(input field number )
I call this func as following

Code: Select all

ageCalc('pa_birthdate','pa_age');
It doesn't work for some reason. Anyone could help ?

Thanks,


Yves
Last edited by yvesf on Thu Jan 05, 2023 1:56 am, edited 1 time in total.
yvesf
Posts: 315
Joined: Sun Mar 14, 2021 8:48 am
Location: Geneva
Has thanked: 87 times
Been thanked: 11 times

Re: Calculate the age

Unread post by yvesf »

Pb solved. Help no longer needed for this script which works as expected. It was a typo with nuSetvalue() instead of nuSetValue() function.
The corrected function is :

Code: Select all

function ageCalc(birth,age_num) {
let o = $('#' + birth);
let d = nuFORM.removeFormatting(o.val(), o.attr('data-nu-format'));
 var dob = new Date(d);  
    //calculate month difference from current date in time  
    var month_diff = Date.now() - dob.getTime();  
      
    //convert the calculated difference in date format  
    var age_dt = new Date(month_diff);   
      
    //extract year from date      
    var year = age_dt.getUTCFullYear();  
      
    //now calculate the age of the user  
    var age = Math.abs(year - 1970);  
console.log('age='+age);
nuSetValue('age_num',age); 

} 
To be put in the setup header of the application as it is used everywhere.
Post Reply