Removing or Disabling Choice List Options

Home/Scripting/Client scripts/Removing or Disabling Choice List Options

Removing or Disabling Choice List Options

One common configuration task in Service-now is to disable (make read-only) or remove certain select options from a choice list of a particular choice field. By far, the most common scenario where I’ve seen this is when a customer wants to restrict access to some ‘Closed’ type of option in a choice list depending on the role of the user. This is so common, in fact, that it has been worked into an Incident Management Best Practices plugin. In general, removing or adding choice list options is pretty easy to do, but there are a few things that you need to look out for. Disabling or enabling choice list options is not as simple just because it’s not a built-in function in Service-now. In this post, I’ll show you how to do both!

Removing/Adding Options

You can remove options from a choice list by using the following function call…

g_form.removeOption(<fieldName>, <choiceValue>);

Here are a couple of practical examples…

//Remove the 'Critical' priority option when some field changes
function onChange(control, oldValue, newValue, isLoading) {
   g_form.removeOption('priority', '1');
}
If you’re removing options in an ‘onLoad’ script make sure that you only remove the option if it is not the currently selected option as shown here.
//Remove the 'Closed' state option if the user is not an admin and state is not 'Closed'
function onLoad() {
   var isAdmin = g_user.hasRole('admin');
   var state = g_form.getValue('state');
   if (!isAdmin && (state != 7)){
      //alert('Current user is not an admin');
      g_form.removeOption('state', '7');
   }
}

If you want to remove ALL options from a choice list you can use the following…

g_form.clearOptions('<FIELD_NAME>');

Options can be added to a choice list by using the ‘addOption’ function call…

g_form.addOption(<fieldName>, <choiceValue>, <choiceLabel>, <targetIndex>);
Note that the ‘targetIndex’ parameter is a numeric, zero-based value that allows you to specify the point in the choice list where an option should be inserted. So, if you had a choice list with 5 options and you wanted your option to be added as the third option, your target index would be the number 2. If your choice list contains a ‘–None–‘ value, you must include that in your count (usually the 0 index). ‘targetIndex’ is an optional parameter. If no target index is specified, then the option will be added to the end of the choice list.

Here’s an example…

//Add the 'Critical' priority option as the second option (--None-- value is option 1) when some field changes
function onChange(control, oldValue, newValue, isLoading) {
   g_form.addOption('priority', '1', '1 - Critical', 1);
}

Disabling/Enabling Options

There is no out-of-box function provided to disable options in choice lists.

The reason for this is that the Chrome browser didn’t support the method and removed the options instead. It is possible to disable choice list options in other browsers though, but you’ll have to provide the function to do so. In order to do that, you can create a new UI Script by navigating to ‘System UI -> UI Scripts’ and entering the following settings:

UI Script SettingsName: DisableEnableOption (Make sure to avoid any special characters in the naming of UI scripts)
Active: true
Global: true
Script:

function disableOption(fieldName, choiceValue) {
   fieldName = g_form.removeCurrentPrefix(fieldName);
   var control = g_form.getControl(fieldName);
   if (control && !control.options) {
      var name = 'sys_select.' + this.tableName + '.' + fieldName;
      control = gel(name);
   }
   if (!control)
      return;

   if (!control.options)
      return;

   var options = control.options;
   for (var i = 0; i < options.length; i++) {
      var option = options[i];
      if (option.value == choiceValue) {
         control.options[i].disabled = 'true';
         break;
      }
   }
}

function enableOption(fieldName, choiceValue) {
   fieldName = g_form.removeCurrentPrefix(fieldName);
   var control = g_form.getControl(fieldName);
   if (control && !control.options) {
      var name = 'sys_select.' + this.tableName + '.' + fieldName;
      control = gel(name);
   }
   if (!control)
      return;

   if (!control.options)
      return;

   var options = control.options;
   for (var i = 0; i < options.length; i++) {
      var option = options[i];
      if (option.value == choiceValue) {
         control.options[i].disabled = '';
         break;
      }
   }
}

Once you have created your global UI Script functions, you can use it in almost the exact same way as the ‘removeOption’ function above. The only difference is that there is no need to prefix the function call with ‘g_form’.

You can disable options from a choice list by using the following function call…

disableOption(<fieldName>, <choiceValue>);

Here are the same examples from above modified to use the ‘disableOption’ call instead of the ‘g_form.removeOption’ call.

//Disable the 'Critical' priority option when some field changes
function onChange(control, oldValue, newValue, isLoading) {
   disableOption('priority', '1');
}

Again, you probably will only want to disable the option if it is not the option selected when the form loads.

//Disable the 'Closed' state option if the user is not an admin and state is not 'Closed'
function onLoad() {
   var isAdmin = g_user.hasRole('admin');
   var state = g_form.getValue('state');
   if (!isAdmin && (state != 7)){
      //alert('Current user is not an admin');
      disableOption('state', '7');
   }
}

Similarly, you can enable options in a choice list by using the following function call. Since the option is not actually removed from the list, it’s not necessary to provide the choice index.

enableOption(<fieldName>, <choiceValue>);

Here’s an example of the ‘enableOption’ call.

//Enable the 'Critical' priority option when some field changes
function onChange(control, oldValue, newValue, isLoading) {
   enableOption('priority', '1');
}
By | 2015-06-17T07:09:06+00:00 February 17th, 2010|Categories: Client scripts|Tags: , , , |36 Comments

About the Author:

Mark has worked in the IT industry since 2002 and with ServiceNow since 2007. He is the founder and creator of SN | Guru and the co-founder of Crossfuze, one of the worlds leading ServiceNow consulting partners. Prior to co-founding Crossfuze, he worked for ServiceNow as a Senior Architect on the Professional Services team. He has personally led dozens of successful implementations encompassing every part of the ServiceNow platform. He is also responsible for designing and developing groundbreaking ServiceNow solutions and best practices in the form of various applications, turnkey solutions, and integrations during his tenure at ServiceNow, Crossfuze and, of course, SN | Guru. These solutions are used today by ServiceNow administrators and consultants alike in hundreds of ServiceNow instances around the world!

36 Comments

  1. sylvain.aspediens March 17, 2010 at 12:23 am - Reply

    Excellent, it works perfectly! Thanks for this article!!!

  2. David Martin June 1, 2010 at 1:27 am - Reply

    Remove option is great, thanks.

    I have a question if I may, I want to do exactly the same hide a Status but only if a Change as been created/related for a Problem. Is this possible? What could I use to check whether a change has been related.

    Thanks

    Dave

  3. Rick Mann March 1, 2011 at 12:55 am - Reply

    Mark

    Have you seen any issues where this type of client script would cause a form not to load correctly with Internet Explorer? I created an onLoad client script with the code below. The script does work with Chrome and Firefox.

    function onLoad() {
     
       var isEwr = g_user.hasRole('ewr_manager');
     
       var ewrStatus = g_form.getValue('u_status');
     

     
       if (!isEwr &amp;&amp; (u_status != 8)){
     
          g_form.removeOption('u_status', '8');
     
       }  
     
       if (!isEwr &amp;&amp; (u_status != 9)){
     
          g_form.removeOption('u_status', '9');
     
       }
     
    }
    • Mark Stanger March 1, 2011 at 1:19 am - Reply

      I haven’t, but I do see some errors in your ‘if’ conditions in this script. I think ‘u_status’ should be changed to ‘ewrStatus’.

  4. Sandy Seegers May 13, 2011 at 3:21 am - Reply

    Mark,

    We use this technique for limiting choice list selection values in several circumstances. However, we’ve run into one big problem with this approach. If we’re working in a situation with extremely slow response times, it is sometimes possible to select a ‘forbidden’ choice value before the Client Script has a chance to load. In fact, I can simulate this if I’m really quick to click on the cancel load button on my browser.

    Right now I’m looking at having to add a Business Rule to enforce the selection list restrictions that I’m trying to accomplish with my Client Scripts. Looking into your crystal ball, do you foresee a possibility that choice list values could be controlled with Access Rules?

    Thanx in advance

    Sandy

    • Mark Stanger May 13, 2011 at 3:49 am - Reply

      I can’t think of a good way to do that with ACLs. The ‘before’ business rule approach with a ‘setAbortAction’ check is what I would use if I were having a similar problem. You might also consider an ‘onChange’ client script to validate the choice. The first place you should look though is at the client scripts and UI policies running on that form and see what you can eliminate or optimize. Even with high latency, I wouldn’t think that you would be having this issue unless you had a ton of other client scripts and policies running.

  5. Tony Balestreri June 14, 2011 at 7:50 am - Reply

    The disableOption works perfectly for firefox and chrome however in internet explorer it does not for me. This happen to anyone else?

    • Mark Stanger June 14, 2011 at 9:40 am - Reply

      I just tested it successfully with IE8 at demo.service-now.com. I’ve never had any reports of issues with IE and these scripts.

      • Richard Bertram May 29, 2013 at 3:11 pm - Reply

        I have confirmed this to be an issue for IE7, but IE8 and later work correctly. Any suggestions on what may be the cause and how to fix it?

  6. Daniel Styer July 5, 2011 at 8:23 am - Reply

    How do you add or remove an opton with a wizard multiple choice field?

    • Mark Stanger July 5, 2011 at 9:22 am - Reply

      @Daniel, This article was intended to address choice fields, not multiple choice variables. I’m not aware of any way to do that directly, though it might be possible. You may try asking on the forums but my advice would be to use a regular choice field if you need to do this.

  7. sandy August 4, 2011 at 4:59 pm - Reply

    i have this code to remove value from hardware_substatus. it works fine when the form is loading but it does not remove “active” value when we change the field on the form. am i missing anything here.

    function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if(g_form.getValue('sys_class_name') != 'u_cmdb_ci_handheld'){
    var ch = new GlideRecord('sys_choice');
    ch.addQuery('name','u_cmdb_ci_handheld');
    ch.addQuery('element','hardware_substatus');
    ch.query();
    while(ch.next()){
    g_form.removeOption('hardware_substatus', 'active');
    }
    • Mark Stanger August 4, 2011 at 6:07 pm - Reply

      If there is an issue, it wouldn’t be with ‘removeOption’ since that works equally well onLoad and onChange. From the script that you pasted I can tell you that you’re missing a couple of closing brackets but I’m not sure if you pasted the entire thing. You’ll just have to troubleshoot the issue to find out. I would start by placing a couple of alerts in that client script to see if the code gets into the ‘if’ statement and to see if it gets to the ‘while’ statement. This would help you to determine where the issue with your script is.
      If the script gets all the way into your ‘while’ statement and still doesn’t work then you’ve probably got some other conflicting script in your system.

  8. Alex Alarcon December 21, 2011 at 4:22 pm - Reply

    Mark, does the addOption() function only work with choice lists or can it work with catalog variables such as a checkbox?

    • Mark Stanger December 21, 2011 at 6:40 pm - Reply

      These functions are designed to be used with standard choice lists only.

  9. Joan June 24, 2013 at 2:09 am - Reply

    Hi Mark,

    I used this script. It works, but my problem is how can I make it reset to the original Value?

    I am working on the Change Request. If the Type = Standard it will only show the State = 5. It works, when I change to other type, but when I go back to Type = Standard it still disabled the choicelist option.

    function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue == ”) {
    return;
    }
    if(newValue !=’Standard’){

    g_form.removeOption(‘state’,’5′);

    }
    }

    • Mark Stanger June 26, 2013 at 6:51 am - Reply

      You should just need to add an ‘else’ statement below your ‘if’ and use the ‘addOption’ method to re-enable the necessary option if the opposite condition applies.

  10. Waqas Mahmud January 23, 2014 at 2:32 pm - Reply

    How can you do for example;

    Category Level 3 = xyz
    AND
    Change Type = abc
    Then Remove Options 1 and 2 from Action field

    I get the OnChange for 1 field, but how do I specify based on 2 fields ?

  11. Waqas Mahmud January 24, 2014 at 7:34 am - Reply

    Basically how would I do a OnChange for a field where 2 conditions need to be met?, saying that fields 1 and 2 both need to change to a certain value for field 3 to disable certain options – is that even possible with a OnChange?

  12. Sachin Shinde April 3, 2014 at 1:38 am - Reply

    How can we hide the choice value on list.

    On form the add7remove options work perfectly but I am not able to hide this values when user edits this records from the list.

    • Mark Stanger April 3, 2014 at 6:52 am - Reply

      You can’t hide them from a list because you can’t run the necessary client scripts there to do so. If you’re hiding choice options, then you also need to restrict list editing for that field with a ‘list_edit’ ACL.

  13. CJohny April 16, 2014 at 4:24 am - Reply

    hi Mark,
    I have a question. I tried to write this script to enable a choice in ‘dev’ in ‘env’ field on a catalog form.

    function onChange(control, oldValue, newValue, isLoading)
    {
    if(newValue ==’Value1′)
    {
    g_form.addOption(‘env’,’dev,’dev’);
    }

    else
    {
    g_form.removeOption(‘env’,’dev’,’dev’);
    }
    }

    And it is working fine. But once the form is submitted, the value is getting removed. It no longer shows that the value is oresent in the field. When i tried to add the choice to the variable field, the choice was visible twice.

    Can you help me?

    • Mark Stanger April 16, 2014 at 8:59 am - Reply

      The removal and addition code is working correctly, but you’re not handling all of the various scenarios associated with it. Your onChange script is also running onLoad, so that’s probably the cause of some of the confusion. You should also only remove an option if it isn’t currently selected.

  14. Tony Nelson June 23, 2014 at 8:54 am - Reply

    The solutions above we use today to remove options from standard choice lists in forms.I have had a request to change some options in an existing Select Box in a Variable Set. Of course any changes to choices in a select box effect existing RITMs that were ordering using the choice I’m trying to remove. I’ve looked up and down and can’t find a good solution on removing/hiding those…can anyone point me to a solution?

  15. Jeff Schodde February 4, 2015 at 11:20 pm - Reply

    I had a problem with the disableOption working correctly. I noticed that you don’t specify “g_form.” like you do for the removeOption. Once I added the “g_form.” like this: g_form.disableOption() it worked.

    Was this intentional?

    • Mark Stanger February 5, 2015 at 4:58 am - Reply

      Thanks Jeff. Yes, ServiceNow has added ‘enableOption’ and ‘disableOption’ to their g_form API since I created this article. You should use the built-in ‘g_form’ options instead.

  16. Prsaanna Kumar Duvvuri May 26, 2015 at 7:55 am - Reply

    I’m facing issue with disable and enable option functions.

    I’ve added in UI script, but, it is working all the browsers except in Chrome. Please let me know how to resolve this issue.

    Thanks & Regards!
    Prasanna Kumar Duvvuri

    • Mark Stanger May 26, 2015 at 8:01 am - Reply

      As noted above, you should use the standard ‘g_form.enableOption’ and ‘g_form.disableOption’ included in ServiceNow. There’s no further need for a UI script.

      • Jeremie Landers October 29, 2015 at 4:11 pm - Reply

        If I read this correctly in the SNow wiki release notes sections, both g_form.enableOption and g_form.disableOption were enabled in Fall 2010 Stable 3, but they were both removed as of the June 2011 Preview 1. If this is correct Mark, your functions are still the only way to perform these tasks.

  17. Prasanna Kumar Duvvuri May 26, 2015 at 8:11 am - Reply

    Hey Mark,

    I already used the g_form before that disableOption. But, I’m getting error like below:

    onChange script error: TypeError: g_form.disableOption is not a function function onChange_kb_knowledge_topic_2(control, oldValue, newValue, isLoading, isTemplate) { if (isLoading) { return; } var topicField = g_form.getValue(‘topic’); alert(topicField); alert(g_scratchpad.isNewsDL1); alert(g_scratchpad.isNewsDL2); if((topicField == ‘News’) && g_scratchpad.isNewsDL1 == true && g_scratchpad.isNewsDL2 == false){ g_form.disableOption(‘category’,’Help Desk Portal Alert’); } if((topicField == ‘News’) && g_scratchpad.isNewsDL1 == false && g_scratchpad.isNewsDL2 == true){ g_form.disableOption(‘category’,’Scrolling News’); } }

    Please let me know how to fix this issue.
    Thanks & Regards!
    Prasanna Kumar Duvvuri

    • Mark Stanger May 26, 2015 at 8:18 am - Reply

      You’ll have to contact ServiceNow support about this one then. I don’t know why that wouldn’t be working but it’s specific to their API or a unique configuration in your instance.

  18. sravani January 20, 2017 at 4:20 am - Reply

    It works perfectly!

  19. Vinoth January 25, 2017 at 5:17 am - Reply

    I want to make the reject action as readonly on choice list UI action. Can any one guide me how to implement this?

  20. Clint Masters August 10, 2017 at 6:15 pm - Reply

    Is there any way to hide an option from a reference field. For example I have a field that looks up groups but in certain scenarios I do not want the user to be able to select some of them. Is there any way that you know of to accomplish this using removeOption or something similar?

  21. Avinash September 20, 2017 at 2:21 am - Reply

    This code does not work in service portal. Is there any workaround to do the same in portal.

Leave A Comment