Quicker Way To Dynamically Add Options

There are many scenarios when you want to dynamically populate a select box with the appropriate options. ServiceNow have even given us a shortcut method to populate the choice field in the GlideForm API using g_form.addOption.

This is usually adequate for populating select fields. However, if you have a large number of values that you need to add, you may notice a performance hit on the end users screen (of course as it’s client side, this is dependant on a number of factors including, but not limited to, browser specification, operating system, machine specification).

This was brought to my attention on a project I was working on and I was tasked with finding a solution. I had one of two routes to go down:

  1. Remove the dynamic select field
  2. Find a more efficient way of adding the options

As the select field was a requirement, I of course went for option 2 (plus it seemed a lot more fun to solve! 🙂 ). Let’s take a closer look shall we…

So, in the debugging of the g_form.addOption, I realised if I replaced g_form.addOption with standard javascript, the operation went a lot quicker. The issue is however, the standard onchange events which ServiceNow throws to handle UI policies, client scripts and even mandatory checks were now failing. So I had to turn to a ‘half-way house’ between pure direct Javascript and ServiceNow’s specific implementation. This is what I was left with:

First, add an On Load client script to the form where you are experiencing performance issues on with the following code:

this.addOption = function(id,displayText,value) {
               id = g_form.resolveNameMap(id);
               var control = $(id);
               var newOption = new Option(displayText, value);
               control.options[control.options.length] = newOption;

Now, where ever you previously used g_form.addOption, simply replace it with this.addOption. The parameters passed in are identical! Give the form another go and hopefully you’ll notice an immediate performance increase! In one example, this reduced the performance of the form from 6 seconds down to 2!

Your mileage might vary so I’ll be interested to know how you get on.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.