Set current date time in catalog item based on other variable

Rick Mann
Tera Expert

I'm creating a catalog item where I want to populate the current date/time if another variable is set to "Yes". I've been working with the following catalog script, but I'm not having success.


function onChange(control, oldValue, newValue, isLoading) {
   if (!isLoading) {
       //alert('new value is ' + newValue);
       if (newValue == 'Yes') {
           g_form.setValue('run_date', nowDateTime());
       }
       if (newValue == 'No') {
           g_form.setValue('run_date', '');
       }
   }
}

Thanks for any help.
3 REPLIES 3

SteveS
Kilo Expert

I think that it should be u_run_date instead of just run_date since it was a user created field.


Jay_Ford
Kilo Guru

Since this is a catalog item as long as your variable name is run_date, you don't need to add the u_.

I think the issue is that you don't have access to gs functions from client scripts, so in order to get nowDateTime() you will have to create a script include like this example (http://wiki.service-now.com/index.php?title=Set_Current_DateTime_In_Field) and call it via an Ajax call in your client script to get the current date time.


Ivan Martez
ServiceNow Employee
ServiceNow Employee

I'd prefer not use the "getXMLWait" method because it locks the browser until the answer is returned. I just tried this in my instance. I created 2 fields, the first field was a Yes/No variable, the second field was a date/time field. Here is the code.

Script Include -

Name: MyDateTimeAjax
Client Callable: true

Script:




var MyDateTimeAjax = Class.create();

MyDateTimeAjax.prototype = Object.extendsObject(AbstractAjaxProcessor, {

nowDateTime: function() {
return gs.nowDateTime();
}
});


Client Script -
Name: set the date
Type: onChange
Applies to: Catalog Item

Script:


function onChange(control, oldValue, newValue, isLoading) {

if(newValue == "Yes"){

var ga = new GlideAjax('MyDateTimeAjax');
ga.addParam('sysparm_name', 'nowDateTime');
ga.getXML(setDateTimeParse);
}

function setDateTimeParse(response){
var answer = response.responseXML.documentElement.getAttribute("answer");
g_form.setValue('my_date_field', answer);

}
}