Calculate Age from DoB in Client Script

escanor
Giga Contributor

I'm trying to create a Client Script to calculate age from DoB like picture below
find_real_file.png

Currently i have no idea to do it lol. I've seen some related posts about that and tried but it's not worked. Pls help me ! Ty

1 ACCEPTED SOLUTION

Harish KM
Kilo Patron
Kilo Patron

I have replied bro

https://community.servicenow.com/community?id=community_question&sys_id=aae1977edb2a1700fff8a345ca9619e8

 

Anyways will post it here

Write a script include

var ageScript = Class.create();
ageScript.prototype = Object.extendsObject(AbstractAjaxProcessor, {

checkAge: function() {
var dob = this.getParameter('sysparam_id');//param from client script
var today = new GlideDateTime();
var todayYear = today.getYearLocalTime();
var bday = new GlideDateTime(dob.toString());
var bdayYear = bday.getYearLocalTime();
var age =todayYear - bdayYear;
return age;
},

type: 'ageScript'
});

 

find_real_file.png

 

Then client script

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}

var ga = new GlideAjax('ageScript');
ga.addParam('sysparm_name','checkAge');
ga.addParam('sysparam_id',newValue);
ga.getXML(Process);
}
function Process(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
alert(answer);
var a = parseInt(answer);
alert(a);
g_form.setValue("age",a);
}

find_real_file.png

 

Regards
Harish

View solution in original post

13 REPLIES 13

Harish KM
Kilo Patron
Kilo Patron

I have replied bro

https://community.servicenow.com/community?id=community_question&sys_id=aae1977edb2a1700fff8a345ca9619e8

 

Anyways will post it here

Write a script include

var ageScript = Class.create();
ageScript.prototype = Object.extendsObject(AbstractAjaxProcessor, {

checkAge: function() {
var dob = this.getParameter('sysparam_id');//param from client script
var today = new GlideDateTime();
var todayYear = today.getYearLocalTime();
var bday = new GlideDateTime(dob.toString());
var bdayYear = bday.getYearLocalTime();
var age =todayYear - bdayYear;
return age;
},

type: 'ageScript'
});

 

find_real_file.png

 

Then client script

function onChange(control, oldValue, newValue, isLoading) {
if (isLoading || newValue == '') {
return;
}

var ga = new GlideAjax('ageScript');
ga.addParam('sysparm_name','checkAge');
ga.addParam('sysparam_id',newValue);
ga.getXML(Process);
}
function Process(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
alert(answer);
var a = parseInt(answer);
alert(a);
g_form.setValue("age",a);
}

find_real_file.png

 

Regards
Harish

SR2
Tera Contributor

Can we do age calculation based on date of birth, with only client script but not using script include.

Harish KM
Kilo Patron
Kilo Patron

Hey bro did the script work or still facing issue?

Regards
Harish

It's still have an issue bro 😞 

find_real_file.png

Btw, I set Age field be Read-only