The CreatorCon Call for Content is officially open! Get started here.

Catalog Item client script - how to change date variable using onChange

jasdwr1
Kilo Contributor

I am creating a Catalog Item with two dates.   The first date has a default value of "javascript:gs.nowDateTime" and the second date variable uses a GlideDateTime function to add 7 days to "today".   All this works fine.   If the first date is changed, I want to add 7 days to the new date and populate the second date variable.   Both date fields are defined as Date.

After searching the Community and trying various methods, I am still at a wall, the second date never changes.   The latest client script I've tried is

function onChange(control, oldValue, newValue, isLoading) {
// return if loading
if (isLoading){
    return;
}

// if start_date new value is blank, return
if (newValue == ''){
    return;
}

var updDate = newValue;
alert('initial date to change ' + updDate);
updDate.addDays(7);
alert('updated date ' + updDate);
g_form.setValue('end_date', updDate);
alert('new end date ' + g_form.getValue('end_date'));
return;

}

Prior to this I tried using the same script in the second date's default, tweaking for use in the client script.

function onChange(control, oldValue, newValue, isLoading) {
// return if loading
if (isLoading){
    return;
}

// if start_date new value is blank, return
if (newValue == ''){
    return;
}

// Get the datetime now
var nowGdt = new GlideDateTime(newValue);

// The name of the schedule
var myScheduleName = '24 x 7';

// The basis of our calculation
var dueDays = 7;
var dueWorkingHours = 24;

// The amount of time we want for the duration
var dueSeconds = dueDays*dueWorkingHours*60*60;
var leadTime = new GlideDuration(dueSeconds*1000);

// Calculate the Due Date!
var dueDateGdt;
var schedRec = new GlideRecord('cmn_schedule');

if (schedRec.get('name', myScheduleName)) {            
        var sched = new GlideSchedule(schedRec.sys_id);
        dueDateGdt = sched.add(nowGdt, leadTime, '');
}

g_form.setValue('end_date', dueDateGdt);
return;

This is the only client script for the catalog item.   Do I need to include something for the addDays or GlideDateTime?

thanks for viewing and helping!

1 ACCEPTED SOLUTION

manikorada
ServiceNow Employee
ServiceNow Employee

Doug,



A simple script to do that is :



var dateMS = getDateFromFormat(newValue,g_user_date_format);


          dateMS += 7 * 24 * 60 * 60 * 1000;


          var newDT = new Date();


          newDT.setTime(dateMS);


          g_form.setValue('end_date',formatDate(newDT,g_user_date_format));


View solution in original post

5 REPLIES 5

Edwin - thanks again, I still have something wrong.



Mani - tried your script and it's working as desired.   Thanks so much!



Again, huge thanks to both for all the assistance.   I'll answer this with Mani's solution.