Show/Hide Form Section by Name

Home/Client scripts, System Definition/Show/Hide Form Section by Name

Show/Hide Form Section by Name

FUJI UPDATE: In the Fuji release, ServiceNow finally fixes this with a standard g_form call! You can now hide form sections using their name like this…

g_form.setSectionDisplay('schedule', false);

The first parameter is simply the name of your section, which should be completely lower-case. Sections including spaces should use an underscore in place of the first space with the rest of the spaces removed. For example, a form section with a label of ‘Schedule and Planning’ would require a parameter of ‘schedule_andplanning’. The second parameter is a true/false boolean that indicates whether the form section should be visible or not.

F

orm sections are a great way to segment information on a form into pieces that make sense to be grouped together. The most common example of the use of form sections is the ‘Comprehensive Change’ form. If you want to learn more about how forms, form sections, and views work I HIGHLY recommend a post I wrote a while ago on the topic. When customers use form sections, the need often arises to be able to show and hide that form section with a client script onLoad or on some changed field trigger.
People have known how to hide these form sections based on an ID number (which corresponded to the order of the form sections on the form). This method works fine, but it fails as soon as you add a new form section or change the ordering of your form sections in some way. Because of this, there has long been a need to hide form sections based on the section name or caption. Nobody has been able to figure out a way to do this…until now. Read on for the details…

First, for reference purposes, I’ll show you the standard, number-based script for hiding form sections.
Hide a form section…
If I wanted to hide the second form section on my form I could use this script…

var sections = g_form.getSections();
sections[1].style.display = 'none';

Show a form section…
If I wanted to show the second form section on my form I could use this script…

var sections = g_form.getSections();
sections[1].style.display = 'block';

FUJI UPDATE: In the Fuji release, ServiceNow finally fixes this with a standard g_form call! You can now hide form sections using their name like this…

g_form.setSectionDisplay('schedule', false);

The first parameter is simply the name of your section, which should be completely lower-case. Sections including spaces should use an underscore in place of the first space with the rest of the spaces removed. For example, a form section with a label of ‘Schedule and Planning’ would require a parameter of ‘schedule_and_planning’. The second parameter is a true/false boolean that indicates whether the form section should be visible or not.

The method for hiding a form section by name is really just a slight change to the way that the form section is selected. Whereas the number-based method returns all form sections in an array, the name-based method selects just that specific form section based on the form section caption. This method utilizes Prototype selectors to target the specific span that the form section resides in based on the ‘tab_caption’ attribute, but the result is the same.

Hide a form section by name…
If I wanted to hide the form section with a name of ‘Schedule’ I could use this script. Just replace ‘Schedule’ with the name of your form section to use it in your environment.

//Hide the section
var section = $$('span[tab_caption_raw="Schedule"]')[0].select('span[id*=section.]')[0];
section.hide();
//Hide the tab
$$('.tab_caption_text').each(function(caption) {
    if(caption.innerHTML == 'Schedule'){
        caption.up('.tab_header').hide();
    }
});

Show a form section by name…
If I wanted to show the form section with a name of ‘Schedule’ I could use this script. Just replace ‘Schedule’ with the name of your form section to use it in your environment.

//Show the section
var section = $$('span[tab_caption_raw="Schedule"]')[0].select('span[id*=section.]')[0];
section.show();
//Show the tab
$$('.tab_caption_text').each(function(caption) {
    if(caption.innerHTML == 'Schedule'){
        caption.up('.tab_header').show();
    }
});

Automatically selecting the shown form section

In some cases you might want to automatically select the form section tab as it is shown. You can also do this through client scripting. I’ve documented that solution here.

Want to learn more about controlling the behavior of tabs and form sections in ServiceNow? Check out these other articles for more information!

By | 2017-03-02T15:26:04+00:00 March 14th, 2011|Categories: Client scripts, System Definition|Tags: |41 Comments

About the Author:

41 Comments

  1. Jim Coyne March 15, 2011 at 9:45 am - Reply

    Nice article Mark, just what I was looking for.

    I took your idea a step further and created 2 UI Scripts that you can call with the name of the section you want to hide or show on any form.

    function u_formSectionShow(sectionName){
       var section = $$('span[tab_caption="Schedule"]')[0].select('span[id*=section.]')[0];
       section.show();
    }
     
    function u_formSectionHide(sectionName){
       var section = $$('span[tab_caption="Schedule"]')[0].select('span[id*=section.]')[0];
       section.hide();
    }
    • Mark Stanger March 15, 2011 at 9:51 am - Reply

      Great idea, and a good use of UI scripts!

    • Billy Matthews March 27, 2014 at 9:42 am - Reply

      Cool stuff. To take it one step further:

      function u_form_section ( section, state)
          var section = $$('span[tab_caption="' + section + '"]')[0].select('span[id*=section.]')[0];
          if (state) {
              section.show();
          } else {
              section.hide();
          }
      }

      then just u_form_section(‘Schedule’, true) to show or u_form_section(‘Schedule’, false) to hide.

      • Mark Stanger March 27, 2014 at 10:07 am - Reply

        Nice solution, and thanks for sharing. No doubt that many of these types of client-side solutions, in wider use in an environment, would be better constructed in functions like this…I’ve used UI scripts in certain cases in the past so that the function and the bulk of the code only had to be declared once in a central location and could then be reused again and again.

      • Dave Greene August 6, 2014 at 3:33 pm - Reply
        function u_form_section( sect, state) {
            var section = $$('span[tab_caption="' + sect + '"]')[0].select('span[id*=section.]')[0];
            if (state) {
                section.show();
        $$('.tab_caption_text').each(function(caption) {
            if(caption.innerHTML == "' + sect + '"){
                caption.up('.tab_header').show();
            }
        });
            } else {
                section.hide();
        $$('.tab_caption_text').each(function(caption) {
            if(caption.innerHTML == "' + sect + '"){
                caption.up('.tab_header').hide();
            }
        });
            }
        }
      • Paul Senatillaka February 27, 2015 at 12:54 pm - Reply

        Tweaked a bit so an undefined error is not thrown and script execution stopped if it doesn’t find the Section.

        function u_form_section (section, state) {
        $$(‘span[tab_caption=”‘ + section + ‘”]’).each(function(section) {
        var secSpan = section.select(‘span[id*=section.]’)[0];
        if (state) {
        secSpan.show();
        } else {
        secSpan.hide();
        }
        });
        }

  2. Tony Fugere March 15, 2011 at 12:18 pm - Reply

    Love it!

    @Jim: +1 on Mark’s response.

  3. Matt Gaide April 4, 2011 at 8:33 am - Reply

    Awesome!

  4. John Gerrard April 14, 2011 at 12:06 am - Reply

    Hi,

    I tried both methods (number and named) to hide and show a form section On Load and On Change, it worked great. However I had an existing UI Policy to show or hide a new unrelated field based on priority and it stopped working ! I deactivated both client scripts and the UI Policy worked again. I reactivated just the On Load script and the UI Policy stopped working again. Has anyone seem similar behavior ?

  5. Michele May 16, 2011 at 8:17 am - Reply

    Can you override the section header color too?

    • Mark Stanger May 16, 2011 at 1:02 pm - Reply

      Yep. I can’t guarantee that this script won’t break in the future because you have to get to some very specific tags to change it, but something like this would work to change the background color of the ‘Schedule’ form section to red.

      var section = $$('span[tab_caption="Notes"]')[0].select('span[id*=section.]')[0].down('tr.header');
      section.style.background='red';
  6. Josh B May 23, 2011 at 8:16 am - Reply

    I’m using this method to hide a form section when a true/false field is changed. Is there a simple way to clear the value of all fields in the section when hidden? Otherwise, if values had been supplied prior to hiding the section, they will be submitted when the form is saved/updated.

    • Mark Stanger May 23, 2011 at 8:55 am - Reply

      You can set the field values one-by-one when the form section gets hidden just by using the standard ‘g_form.setValue’ or ‘g_form.clearValue’ call. You can check out client scripts on the wiki for more details.

  7. Jim Uomini August 4, 2011 at 4:09 pm - Reply

    I have one client who now has five tabs on their form. I set up a script using this technique that hides all of the tabs and then shows only the one that corresponds to the selection in the Type field. This way, whenever they add another record producer, all I have to do is add on to the end of the script and I can hide another tab without worrying about the order. I had used the old technique before, but it seemed to breakdown when I got beyond two or three sections.

    Thanks Mark, very helpful.

    • Mark Stanger August 4, 2011 at 6:02 pm - Reply

      Awesome Jim! That’s great to hear. I’m glad that it’s helped.

  8. Chuck Tomasi November 14, 2011 at 10:11 am - Reply

    FYI – I tried the two lines above:

    var section = $$('span[tab_caption="Schedule"]')[0].select('span[id*=section.]')[0];
    section.hide();

    and found that view specific client scripts stopped working when this stuff was present. I combined it with the “make variables read-only” to logically check “if there are any variables, make them read-only. Else, hide the section.” When I commented out the lines to hide the section, the view specific

    • Mark Stanger November 14, 2011 at 12:27 pm - Reply

      You’ve definitely got to watch for that with any client script you create. The elements that the script tries to access need to be on the form or you can have errors. One way to deal with this is to use the ‘Global’ checkbox along with a specific view name indicating where the script should run. Another way is to put your code in a try-catch block so that the error doesn’t break processing of other scripts.

  9. Chris Haslage January 23, 2013 at 10:57 am - Reply

    This works, still works fine. As long as they keep doing this then it should work. That’s cool and all… But there is a double space now since we hid the tab, and it looks a little ugly:

    So, is there a way to get a count of what the tab is, then subtract 1 for the GIF and hide? That should solve the issue, but not quite sure how to do that.

    Thanks!

    • Mark Stanger January 23, 2013 at 11:07 am - Reply

      Unfortunately, I don’t have any simple way to handle that. I’ve written a script for that before, but it wasn’t as clean as I like. This is really something that SN should resolve though by allowing you to target the tab and the space all at once.

  10. Phil Wright March 21, 2013 at 2:37 pm - Reply

    How about a script to collapse containers on a catalog form. Not all containers but specific named containers.

    Thanks,
    phil

    • Joshua Bice December 10, 2014 at 8:13 am - Reply

      Phil,

      I use an onLoad client script with the following message:

      toggleVariableSet(”);

      You can use a var = g_form.getReference(”); Then a .sys_id if you need to do it without hardcoding the sys_id.

  11. Troy December 6, 2013 at 10:06 am - Reply

    Hello,

    I’m trying your script, but it’s not working for me. I want it to hide a section on load on the sc_task form if the cat_item is not EEC – Tools on Demand. (That’s the name of my section as well.) Below is my script. Any thoughts? Thank you.

    function onLoad() {
    //Type appropriate comment here, and begin script below
    if(g_form.request_item.cat_item.getDisplayValue() == ‘EEC – Tools on Demand’){
    var section = $$(‘span[tab_caption=”EEC – Tools on Demand”]’)[0].select(‘span[id*=section.]’)[0];
    section.show();
    }
    else{
    //var section = $$(‘span[tab_caption=”EEC – Tools on Demand”]’)[0].select(‘span[id*=section.]’)[0];
    section.hide();
    }
    }

    This shows all the fields on our form, ignoring the UI Policies in place.

    Troy

  12. Dominik Simunek March 24, 2014 at 10:14 am - Reply

    Mark, thanks for this great article. The possibility to hide the whole section is really useful but we had one problem with it once a translation was activated because of different caption/title used for the form section. Then form section was not found and the functionality did not work. However it looks that there is easy fix for that to use “tab_caption_raw” attribute instead of “tab_caption” in the selector because of the fact that “tab_caption_raw” contains English version of the title even if user has different language selected so it is not dependent on the user’s preferred language.

    • Mark Stanger March 24, 2014 at 10:50 am - Reply

      Awesome, thanks for the tip! I’ve modified the scripts above with your solution.

    • Saritha May 18, 2015 at 4:28 pm - Reply

      Thanks a lot for the solution. I was also having the same issue once we enabled translations.

  13. Leo June 13, 2014 at 3:07 am - Reply

    Mark, this is not working for Dublin release. do you have any alternative solution to hidesection from client sctipt? if yes than that would be great help.
    Cheers!!!

    • Mark Stanger June 13, 2014 at 7:37 am - Reply

      Looks like the section is still removed correctly but the tab itself isn’t when trying to manipulate visibility by tab name. I’ve adjusted the scripts above to remove the tab as well. This should work in any instance version.

  14. Pavan Kottam November 11, 2014 at 10:40 am - Reply

    Does this work on Mobiles? Sections doesn’t even show up in mobiles.

    • Mark Stanger November 11, 2014 at 10:48 am - Reply

      The mobile interface has a completely different UI and scripting API. While this may work on mobile devices, it has not been specifically coded for, or tested against the ServiceNow mobile, smartphone, or tablet interface.

  15. Pavan Kottam November 11, 2014 at 11:21 am - Reply

    Thanks Mark. Tablet interface worked fine but mobile interface did not work.

  16. SimonB July 15, 2015 at 1:41 am - Reply

    Quick correction if you have mult-word section headings you only need to replace the first space with an underscore all subsequent spaces should be removed, i.e. “Major Incident Notes” becomes major_incidentnotes

    http://wiki.servicenow.com/index.php?title=GlideForm_%28g_form%29#setSectionDisplay&gsc.tab=0

  17. Ayyappa Swamy September 8, 2015 at 5:44 am - Reply

    Hi Mark,

    I am working on Fuzi instance. In my requirement i am using below methods to hide the section on RITM table, And i am able to hide the section also. But while using these methods i am not able to set the menu list on the form and Filed dictionary options using right click.

    1.var sections = g_form.getSections();
    sections[1].style.display = ‘none’;

    I am using your below script

    2.g_form.setSectionDisplay(‘variables’, false);

    I am using below your script to hide the section but no luck. It would be great help if you provide me the fix.

    //Hide the section
    var section = $$(‘span[tab_caption_raw=”Variables”]’)[0].select(‘span[id*=section.]’)[0];
    section.hide();
    //Hide the tab
    $$(‘.tab_caption_text’).each(function(caption) {
    if(caption.innerHTML == ‘Variables’){
    caption.up(‘.tab_header’).hide();
    }
    });

    Regards,
    Ayyappa Swamy

    • Hi Ayyappa Swamy, May 13, 2016 at 9:07 am - Reply

      Currently we are on Eureka and planning to go for Geneva. So in Geneva I am facing the same issue..
      like Menu list and right click broken.
      Have you figured out this problem?
      Thanks

  18. Andrew Barnes September 10, 2015 at 12:35 pm - Reply

    Amend the Fuji instructions:
    As SimonB points out – the naming convention for sections with spaces is actually different than you list. Only the first space gets replaced with underscore – the rest are simply removed – http://wiki.servicenow.com/index.php?title=GlideForm_(g_form)#setSectionDisplay&gsc.tab=0

    • Mark Stanger September 10, 2015 at 1:37 pm - Reply

      Thank you. I’ve made the correction above.

      • Dale Hynes December 14, 2015 at 9:33 pm - Reply

        Mark – should that be corrected in both of the yellow highlighted areas above ?

        The 2nd Fuji update still reads “Sections including spaces should use underscores in place of spaces”.

  19. Nixie October 16, 2015 at 12:56 am - Reply

    For Slush bucket, to hide buttons we did:
    var eps = document.querySelectorAll(‘#ep’);
    eps[0].rows[0].style.display=”none”; //hide buttons

    Now after Fuji patch upgrade, we cannot read property ‘0’ of undefined.
    Is this also issue related with this?

  20. Kay Defa December 30, 2015 at 3:47 pm - Reply

    Thanks – fixed my problem in Geneva.

  21. John Cooper January 5, 2016 at 2:35 pm - Reply

    I have tried almost every variation that has been presented here…I am trying to limit by role who can see a certain tab. I have used a business rule(display rule) to try and set a true false indicator on the person having tne desired role. then passing that along to get the if then to work. unfortunately i am not getting anywhere….also i am currently on Eureka. Will be moving to Geneva end of Q1

Leave A Comment