On-The-Fly Event Creation in ServiceNow

Recently I was doing some troubleshooting for an onChange script and trying to figure out why it (or rather it’s event) wasn’t firing. In my digging I came across the code that is responsible for registering events and then kicks off the corresponding scripts. I can’t think of a lot of great scenarios off the top of my head, but perhaps when one field changes, you want the system to then start monitoring for 2 other fields to change (maybe user has to do something in a sequence?); just throwing ideas against the wall but you get the idea; keep it in your virtual toolbox ;).

First we throw our script into a function (should look familiar) only difference to the usual is that we are giving it a name (instead of just “onChange”). In this case we’re naming it “onChange_incident_script” but the name can be whatever you want. Next, we will instantiate a GlideEventHandler object. This object will raise our event and call the script when it fires, it expects 3 parameters: The name of the event handler, the script to run, and the field (in the format of table.field) to monitor:

function onChange_incident_script(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue == '') {
    jslog('JM: Running Script from on-the-fly event. Original Value was: ' + oldValue);
    //Your code here...
var thisHandler = new GlideEventHandler('onChange_incident_impact_change', onChange_incident_script, 'incident.impact');

With that said, some of you may be thinking, well why can’t we just use jQuery and do the same thing? Yes, for the most part, however you wouldn’t get the nifty “control, oldValue, newValue, isLoading, and isTemplate” variable data to play with. Just for those curious minds out there, here’s how we could do the close to the same thing in jQuery (minus the extra SN objects):

//we need to use double backslashes to escape the periods in the selector
jQuery('#element\\.incident\\.impact').on('change', function() {
    jslog('JM: Running Script from on-the-fly event. Original Value was: ' + oldValue);
    //Your code here...

Leave a Reply

Your email address will not be published. Required fields are marked *