The Zurich release has arrived! Interested in new features and functionalities? Click here for more

Onchange client script for date validation

Ak8977
Tera Expert

I have two date time fields "In Time" and "Out Time", the out time would be one hour from the In Time. 
I created a on change client script on In Time field. I used the following script, but it was not working.

var timein = g_form.getValue('in_time');

var timeout = g_form.getValue('out_time');

if (timeout === '') {
var timeinDate = new GlideDateTime(timein);
timeinDate.addSeconds(3600); 
g_form.setValue('time_out', timeinDate);

}

1 ACCEPTED SOLUTION

Ankur Bawiskar
Tera Patron
Tera Patron

@Ak8977 

you want to populate Out time with adding 1 hour to In Time right?

if yes then you can do this with simply onChange client script and no GlideAjax required

var timein = g_form.getValue('in_time');
var dateMS = getDateFromFormat(timein, g_user_date_time_format);
dateMS += 1 * 60 * 60 * 1000; // 1 means 1 hour here
var newDT = new Date();
newDT.setTime(dateMS);
g_form.setValue('time_out', formatDate(newDT, g_user_date_time_format));

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

View solution in original post

8 REPLIES 8

Peter Bodelier
Giga Sage

Hi @Ak8977,

 

You are trying to use server side code (new GlideDateTime) in a client script. That's not going to work.

 

You will have to create a GlideAjax call to a script include in order to do use this logic.

 

See GlideAjax | ServiceNow Developers for your reference.


Help others to find a correct solution by marking the appropriate response as accepted solution and helpful.

Harish Bainsla
Kilo Patron
Kilo Patron

function onChangeInTime() {
var timein = g_form.getValue('in_time');
var timeout = g_form.getValue('out_time');

if (timeout == '') {
var timeinDate = new GlideDateTime(timein);
timeinDate.addSeconds(3600);
g_form.setValue('out_time', timeinDate.toString());
}
}

if you get answer please accept solution and mark helpful

@Harish Bainsla 

 

It's client side. GlideDateTime won't work.


Help others to find a correct solution by marking the appropriate response as accepted solution and helpful.

sorry i miss understand question i just do modification in his code