Modifying the Label of Form Fields With Client Scripts

Home/Script includes, UI scripts/Modifying the Label of Form Fields With Client Scripts

Modifying the Label of Form Fields With Client Scripts

Please note that with the introduction of the Service Portal, many client-side scripting methods have been deprecated. The solution described in this article can now be accomplished using the ‘setLabel()‘ method. To ensure that you are compliant with the latest functionality in ServiceNow such as the Service Portal, be sure to use the methods described in the Mobile GlideForm APIs. Just make sure you set the ‘UI type’ field on the client script form to ‘Both‘.

H

ere’s a quick tip for a Monday. This post comes in response to a question on the ServiceNow forums asking if it is possible to change the label of a field dynamically based on some record criteria (such as record type). It is possible, and this post will show you how it can be done.
Dynamic Field Label

First, you should know that you can right-click any field and personalize the label for that field. For extended tables (such as incident) you can override the label for a higher-level table (such as task) just by changing the table name on the label record and doing an ‘Insert’ rather than a save. The question that I’ll address in this post is different than both of those scenarios though. What if you have a label that you want to change based on the user viewing the record? What if you need to change the label based on some criteria unique to that table (such as change type or incident priority)? In that case, you can’t simply modify the label record because you’ve got a narrower scope within that table that you need to work with.

The answer is client scripting. With a client script you can target any field on the form and modify its label. I’ve created a ‘changeFieldLabel’ function for this purpose. The function takes 4 possible parameters to allow for changing of the label text, color, and font weight.

Here’s an example that you could use in an ‘onLoad’ client script to change the ‘Description’ field label on a Change request form…

function onLoad() {
//Change the description label to 'My New Label' with bold red text
changeFieldLabel('description', 'My New Label', 'red', 'bold');
}

function changeFieldLabel(field, label, color, weight){
try{
var labelElement = $('label.' + g_form.getControl(field).id);
labelElement.select('.label-text').each(function(elmt) {
elmt.innerHTML = label + ':';
if(color)
elmt.style.color = color;
if(weight)
elmt.style.fontWeight = weight;
});
}catch(e){};
}

Of course, this is much more accessible if you include it in a global UI script. If you’re going to use this a lot I recommend setting up a global UI script with the following function…

function changeFieldLabel(field, label, color, weight){
try{
var labelElement = $('label.' + g_form.getControl(field).id);
labelElement.select('.label-text').each(function(elmt) {
elmt.innerHTML = label + ':';
if(color)
elmt.style.color = color;
if(weight)
elmt.style.fontWeight = weight;
});
}catch(e){};
}

Then you can invoke the function from any form with a single line.

If I wanted to change the label of the ‘description’ field to ‘My New Label’ I could do it like this…

changeFieldLabel('description', 'My New Label');

If I wanted to change the label to a bold green color I could do it like this…

changeFieldLabel('description', 'My New Label', 'green', 'bold');

Changing the label of a catalog variable

The principles described above can also be applied to catalog variables using catalog client scripts. The primary difference is in the way the elements need to be selected from the DOM. Here’s an example script…

function onLoad() {
//Change the description label to 'My New Label' with bold red text
changeFieldLabel('description', 'My New Label', 'red', 'bold');
}

function changeFieldLabel(field, label, color, weight){
try{
var labelElement = $('label_' + g_form.getControl(field).id);
labelElement.select('.sn-tooltip-basic').each(function(elmt) {
elmt.innerHTML = label;
if(color)
elmt.style.color = color;
if(weight)
elmt.style.fontWeight = weight;
});
}catch(e){};
}
By | 2017-07-13T07:41:20+00:00 October 10th, 2011|Categories: Script includes, UI scripts|Tags: , |69 Comments

About the Author:

69 Comments

  1. Sharee October 10, 2011 at 6:08 pm - Reply

    This is great! Thanks!

  2. Another great bit of functionality November 4, 2011 at 6:49 am - Reply

    Is it possible to change the table label using something similar?

    • Mark Stanger November 4, 2011 at 7:51 am - Reply

      It is possible. You should be able to change the table label of a form (the first form section label) with a script like this…

      var currentLabel = 'Incident';
      var newLabel = 'Changed Incident Label';
      var labelEl = $$('.form_header')[0];
      var newHTML = labelEl.innerHTML.replace(currentLabel, newLabel);
      labelEl.innerHTML = newHTML;
      • joe September 22, 2015 at 8:42 am - Reply

        what about related list labels? I know you can set a label by configuring the list control, BUT is it possible to have the same related list (relationship) on 2 different views (of the same table) and have them labelled differently?

  3. AdminPro December 7, 2011 at 12:00 pm - Reply

    Is there a way to do the same thing with a catalog item – record producer for a variable?!

    • Mark Stanger December 7, 2011 at 12:29 pm - Reply

      There is, but not with the scripts here. The table structure and element IDs are different in the service catalog. I don’t have a script to do that at the moment.

      • Feroz January 13, 2015 at 11:04 pm - Reply

        Nice work!, What does the $ & $$ means in above script?

        • Mark Stanger January 14, 2015 at 6:55 am - Reply

          Good question. That comes from the ‘prototype’ javascript framework, which is bundled with ServiceNow. They basically allow you to target specific elements on the page for manipulation. Check out the prototype API for more details.

          http://api.prototypejs.org/

  4. AdminPro December 7, 2011 at 12:40 pm - Reply

    Mark,
    Thanks for your reply. Ive just figured it out with some hints from your other post.

    • Mark Stanger December 7, 2011 at 12:42 pm - Reply

      Care to post your script here? That would be a nice one to have.

  5. AdminPro December 7, 2011 at 1:30 pm - Reply

    With pleasure,
    Here it is:

    function onLoad() {
       // gaining control of the variable in question with calling the getControl function and selecting the label
       var field = 'description';
       var labelElement = $('label_' + g_form.getControl(field).id).select('label')[0];
       // In this area you can adjust all of the css related styles
       labelElement.style.color = 'blue';
       labelElement.style.fontStyle = 'italic';
       labelElement.innerHTML = 'My New Label';
    }
    • Mark Stanger December 7, 2011 at 2:26 pm - Reply

      Nice work! I collapsed your scripts into a single one (since onLoad and onChange are very similar) and modified it a bit for consistency with the ones above. Looks like it works great though. Thanks for sharing!

    • Johan January 17, 2012 at 12:40 am - Reply

      Thank you very much for this!

    • SNnoobie December 12, 2012 at 3:13 pm - Reply

      This is great AdminPro! However, I’m having a hard time wrapping my mind around turning it into a callable(within another client script) or global UI Script. I’m working on a catalog form where I’m going to want to use this function conditionally for multiple fields. Any help you can provide would be greatly appreciated.

      Thanks!

      • aricw December 13, 2012 at 9:21 am - Reply

        SNnoobie, this should help.

        function ChangeLabel(field, color, style, text){
           // gaining control of the variable in question with calling the getControl function and selecting the label

           var labelElement = $('label_' + g_form.getControl(field).id).select('label')[0];
           // In this area you can adjust all of the css related styles
           if(color){
           labelElement.style.color = color;
           }
           if(style){
           labelElement.style.fontStyle = style;
           }
           if(text){
           labelElement.innerHTML = text;
        }
    • Sherard Pulmano October 27, 2015 at 7:19 am - Reply

      AdminPro/Mark,

      I notice this works for variables that are not within containers. I am able to do this for variables that are placed straight onto the item. How do I find what Element I need to change when it is part of a variable container? I’m not experienced in DOM and not understanding how to find this Element?

  6. Steve Arnold September 17, 2012 at 12:52 pm - Reply

    Mark, any chance something like this could be done to a change the name of a list view column header?

    • Mark Stanger September 17, 2012 at 1:51 pm - Reply

      Hey Steve,
      There’s no good way that I know of to do this. Client scripts cannot be run from a list view.

  7. ND February 19, 2013 at 8:06 am - Reply

    Hi Mark,

    Can we change the section label similarly. I tried using below, but it didn’t help :

    var sections = g_form.getSections();

    sections[1].innerHTML =’test’;

    Regards,
    ND

  8. Amisha Parekh April 19, 2013 at 12:29 pm - Reply

    Hi Mark,

    Is it possible to change Field Label in List Layout?

  9. Xavier February 20, 2014 at 5:10 am - Reply

    Hey Mark, is there any way to add a label in the form sections just like a label on catalog request page…..

    One of our clients wanted to differentiate the fields by adding label, please help me out if there is a way to do so

  10. Priyanka February 27, 2014 at 11:15 pm - Reply

    Can anyone explain the functionality of the above code plzz…

    labelElement.select(‘label’).each(function(elmt) {
    elmt.innerHTML = label + ‘:’;
    });

    • Mark Stanger February 28, 2014 at 5:42 am - Reply

      That’s just using the Prototype API to go through all of the DOM nodes in the label element and adjust the inner text to be the text of your new field label. You can search for ‘prototype API javascript’ on google to find out more about those DOM selectors.

  11. Gary April 17, 2014 at 12:11 pm - Reply

    To change the hint (on hover text):

    function changeFieldHint(field, newtitle){
        var fieldFormName = g_form.getTableName() + "." + field;
        var fieldLabelName = "label." +  fieldFormName;
        try{
            var labelElement = $(fieldLabelName);
            labelElement.title = newtitle;
        }catch(e){
            alert("Error:" + e)
        };
    }
  12. AricW April 17, 2014 at 3:05 pm - Reply

    Hi All!
    I’m trying to apply this script to change the slush bucket labels (left and right), but nothing I’m doing seems to work. Has anyone managed to do this successfully, or do they know how to?

    //left element id = validate_select_0_title_row
    //right element id = validate_select_1_title_row   
    function onLoad() {
       //Change the description label to 'My New Label' with bold red text
        var varName = 'validate';  
        var leftBucket = $(varName + '_select_0');
        var rightBucket = $(varName + '_select_1');
        var left2 = 'validate_select_0_title_row';
        var right2 = 'validate_select_1_title_row';
        var leftTitle = 'Not Valid';
        var rightTitle = 'Valid';  
       changeFieldLabel(left2, leftTitle, 'black', 'bold');
       changeFieldLabel(right2, rightTitle, 'black', 'bold');  
    }

    function changeFieldLabel(field, label, color, weight){
       try{
          var labelElement = $('label_' +  g_form.getControl(field).id);
          labelElement.select('label').each(function(elmt) {
             elmt.innerHTML = label;
          });
          if(color)
             labelElement.style.color = color;
          if(weight)
          labelElement.style.fontWeight = weight;
       }catch(e){};
    }
  13. David C June 4, 2014 at 2:03 pm - Reply

    Hey Guys I am attempting to rewrite the label if a user has itil role..
    however I believe the syntax maybe off.. can you help?
    the field name is called u_comments

    function onLoad() {
       if (!g_user.hasRole("itil"))
          return;

        var field = 'u_comments';
        var fieldFormName = g_form.getTableName() + "." + field;
        var fieldLabelName = "label." +  fieldFormName;
        var ctrl = $(fieldLabelName);
       if (!ctrl)
          return;
       var label = ctrl.select('label')[0];
       if (!label)
          return;
       var s = label.innerHTML;
       label.innerHTML = s.substring(0, s.length - 1) + ' (' + getMessage('Customer visible') + '):';
       //label.setStyle({fontWeight:"bold"});
    }
    • Mark Stanger June 4, 2014 at 2:55 pm - Reply

      Looks like you’re combining what we’ve got here with an out-of-box script. This should work better…

      function onLoad() {
         if(!g_user.hasRole('itil'))
             return;

         //Change the description label to 'My New Label' with bold red text
         changeFieldLabel('u_comments', 'My New Label', 'red', 'bold');
      }

      function changeFieldLabel(field, label, color, weight){
         try{
            var labelElement = $('label.' +  g_form.getControl(field).id);
            labelElement.select('label').each(function(elmt) {
               elmt.innerHTML = label + ':';
            });
            if(color)
               labelElement.style.color = color;
            if(weight)
            labelElement.style.fontWeight = weight;
         }catch(e){};
      }
      • Shane C July 5, 2017 at 3:10 pm - Reply

        Any way to loop through all of my elements that begin with “u_”, and color them?
        I see from the above you’re just calling out the u_comments field, but I’d like to grab all of my custom fields.

  14. Joe July 2, 2014 at 12:02 pm - Reply

    This is great. Thank you for sharing.
    How would you go about changing a catalog variable label on a catalog task? I used the catalog variable code above and it works great on the catalog item submission form. When trying to apply it to the task generated by this particular item in an onLoad CS, i can not get it to work.
    I’ve tried this function call, but to no avail:

    changeFieldLabel(‘variables.requested_for’, ‘Requestor’);

    • Mark Stanger July 2, 2014 at 12:42 pm - Reply

      Unfortunately, ServiceNow hasn’t given us a good way to get at those variable elements on the standard forms. It’s technically possible, but it’s a pretty bad hack that would be likely to break or cause future issues so it’s not something I can recommend or would even spend the time to code up.

  15. Joe C September 8, 2014 at 11:47 am - Reply

    This will sound strange but what about form sections? Is it possible to relabel the first “annotation/separator” that typically would share the same name as the tab caption?

    For instance, say a form section is captioned “A/B” and it displays as such when tabbed. Any ideas on the possibility of changing the first form header/separator from “A/B” to just display “A”?

    • Mark Stanger September 8, 2014 at 1:45 pm - Reply

      Not a strange question at all. In fact, it’s been asked here before! Check out the top of the comments section here for some code to get you started.

  16. Belinda January 9, 2015 at 7:14 am - Reply

    Mark,

    This is excellent – thanks so much for this.

    Is it possible to call the function and not change the text of the current label (I only want to change the color)? If I just use the current label text as the function parameter then it loses my hyperlink set up on the original label.

    Thanks in advance for your assistance!

    • Mark Stanger January 9, 2015 at 7:54 am - Reply

      I think the problem is that you’re trying to use this on a field that includes a hint and URL link in the label. Because of the way this works, it will replace the link as well. I’ve done some testing with it to see if I could fix it, but it looks like it’s not a simple workaround. Unfortunately, links in labels will be overwritten with this approach.

      • Belinda January 9, 2015 at 8:00 am - Reply

        Thanks for checking into it I really appreciate you taking time to look at it.

        Have a great day!

  17. Shipra January 18, 2015 at 10:35 pm - Reply

    Is there a way to change the label dynamically on the basis of some other value. Like I have a Region dropdown list and on the basis of value in Region I wanted populate label in another field. Say if Region is “Africa”, my next label should say which location in Africa?

    • Mark Stanger January 21, 2015 at 9:36 am - Reply

      Yes, that should be fairly simple using the code provided in this article in an ‘onChange’ client script that responds to a change in the field containing the ‘Region’ values.

  18. Sam Brown January 21, 2015 at 6:34 am - Reply

    Hi Mark, Thanks for the above, I’ve slightly modified this to set the backgroundColor of the label as below:

    labelElement.style.backgroundColor = color;

    I’m struggling on fields which automatically flip the label above the field i.e. 1000+ character string fields, the result of is that half the label background changes color rather than the whole label!

    I’ve tried using label_left and label_right with no success, any thoughts?

    S

    • Mark Stanger January 21, 2015 at 9:45 am - Reply

      Now you know why I didn’t include it in the examples :). Label backgrounds vary, but you should be able to get it to work like this…

      labelElement.style.backgroundColor = color;
      labelElement.next().style.backgroundColor = color;

      • Sam Brown January 23, 2015 at 7:06 am - Reply

        Thank you Mark, that did the trick

        S

  19. Raghu February 16, 2015 at 12:23 am - Reply

    Hi Mark,

    I am trying to push some of the field label’s into another field, field name(column name) is working fine but unable to print field label.
    In Business rules can we do this? access of field label?

    Regards,
    Raghu

  20. Pradeep Arora April 3, 2015 at 1:55 pm - Reply

    Worked Perfect…….

  21. Eric K July 13, 2015 at 1:12 pm - Reply

    Is there any reason the first script would not work in Fuji Patch 3? I checked all other client scripts running on incident and task and nothing looks like it would cause a conflict.

    • Mark Stanger July 13, 2015 at 1:32 pm - Reply

      I don’t know of any reason why it wouldn’t work. I just tested on a clean demo instance and it worked fine there. You could try the same just to verify. Usually if a client script isn’t working you can find some clues in the browser error console so I’d check there.

  22. Jan KC August 27, 2015 at 7:59 am - Reply

    Hey Mark,

    Great site you got. Came here lots of times when the wiki did not solve my issues.

    I have a record producer where I modified the labels with a catalog client script as you explained above.
    When the user submits the incident I would like to grab the modified label and insert it in the incident description.
    I know how to get the data from the field, but if I try to get the label with producer.variablename.getLabel() I get NULL.
    Do you know if it is possible to retrieve the modified label?

    • Mark Stanger August 27, 2015 at 9:35 am - Reply

      This script just changes the label client-side so there’s no access to it when you’re using the server-side record producer script. The only way you could get to it is if you used something like an ‘onSubmit’ client script to put the label value in a field so that it would be available to the producer script.

      • Jan KC August 31, 2015 at 6:59 am - Reply

        Thanks Mark! That might just do the job..

  23. Julie Devick January 28, 2016 at 7:34 am - Reply

    I got your initial script to work changing a variable label on a catalog item. We have a global variable set for attachments with a real generic label “Please attach any pertinent data”. I would like to be able to still use the variable set but change the label. Is this a case where I need to dotwalk from the variable set to get to the object?

    I tried just using the variable set field name and no joy. Works great on regular variables though.

    • Mark Stanger January 28, 2016 at 8:25 am - Reply

      This one needs to be done a bit differently. It’s so much of a hack that it’s likely to break in the future so I’m not even sure that you’ll want to use it. Here’s a quick example that should allow you to change the variable set text. Color and styling is even more problematic in this case so it’s not included.

      function onLoad() {
         //Change the description label to 'My New Label' with bold red text
         changeVarSetLabel('common_comments', 'My New Lab', 'red', 'bold');
      }

      function changeVarSetLabel(field, label, color, weight){
         try{
            //Fix label spacing
            label = ' ' + label + ' ';
            var labelElement = $('status.' +  g_form.getControl(field).id);
            labelElement.nextSibling.nodeValue = label;
         }catch(e){};
      }
  24. Anil July 8, 2016 at 12:12 am - Reply

    Dear Mark,

    This has been really helpful. Can I just do a section of the catalog item -> Variable Label as bold and rest as normal.

    for example if this is my catalog item -> variable label “Test Label Bold text” in this text I want only Bold word to appear in bold, rest should be normal.

    Please suggest.

    • Mark Stanger July 8, 2016 at 12:37 am - Reply

      Only thing I can think of that might work is just to replace the label text with label text in ‘‘ bold tags.

  25. Tina August 23, 2016 at 8:20 am - Reply

    Mark,
    I need to underline my text as well. How would I do that?

    Thanks!

    • Underline Text October 10, 2016 at 11:55 am - Reply

      Tina,
      I have made a few adjustments to Mark’s UI Script to achieve the underlined text.

      function changeFieldLabel(field, label, fontColor, weight, bgColor, border, padding, fontSize, decoration){
          try{
             var labelElement = $('label.' +  g_form.getControl(field).id);
             labelElement.select('.label-text').each(function(elmt) {
                elmt.innerHTML = label;
                if(fontColor)
                   elmt.style.color = fontColor;
                if(weight)
                   elmt.style.fontWeight = weight;
                if(bgColor)
                   elmt.style.background = bgColor;
                if(border)
                   elmt.style.border = border;
                if(padding)
                   elmt.style.padding = padding;
                if(fontSize)
                   elmt.style.fontSize = fontSize;
                if(decoration)
                   elmt.style.textDecoration = decoration;
             });
          }catch(e){}
      }

      Then you just need to add the correct format in your client script with the correct parameters:

      changeFieldLabel(‘u_tractor’, ‘Old Road Tractor’, ‘white’, ‘bold’, ‘black’, ‘1px dashed white’,’0 5px’,”,’underline’)

  26. Kristen August 24, 2016 at 2:21 pm - Reply

    Hi Mark,

    This was super helpful for a form I’m building. I’m wondering how I would make the required asterisk show on the field? The field is already set to mandatory, but when the label is changing, that red asterisk is disappearing. I tried digging around online, but wasn’t successful in figuring it out.

    Thanks!

    • Mark Stanger August 24, 2016 at 4:06 pm - Reply

      It’s a bit different for the asterisk indicators on Fuji and beyond. I just updated the code above with some versions that should work better. Give it a try and let me know how it goes.

  27. Divya May 12, 2017 at 3:58 am - Reply

    Hi Mark,

    I have a lengthy choice Label for one of my fields . I want to display a HINT when we hover over the selected choice .

    Please note i don’t want a HINT when i am actually selecting a value from Drop down ( i know we can just add Hint in this case)

  28. Naveen May 19, 2017 at 10:41 am - Reply

    Hi Mark,

    This script is not working to change variable type ‘Label’.
    i.e. Label field’s label.

    Please suggest If there is any way to do this.

  29. Kumarr Satyam May 23, 2017 at 2:48 am - Reply

    Hello Mark,

    I have to change my Section Name dynamically based on some conditions . Form is normal . pretty much like incident .

    How can i perform it . Please specify through example.

  30. Mark June 7, 2017 at 2:17 pm - Reply

    This script not working in Istanbul release

    • Jim Pisello July 14, 2017 at 10:53 am - Reply

      Hi Mark,

      We’ve added a notice to the top of this article to note that the methods in this post have been deprecated in the latest ServiceNow releases.

  31. Pallabi Mitra June 14, 2017 at 2:52 pm - Reply

    It is not working in Service Portal. Is it a known issue or I have to do something else

  32. Steven July 13, 2017 at 7:01 am - Reply

    Mark,

    Script works great in the ITIL view of ServiceNow, but doesn’t work in the Service Portal. Any fixes for that?

    • Jim Pisello July 13, 2017 at 7:43 am - Reply

      Hi Steven,

      For Service Portal you’ll need to use the new Mobile GlideForm APIs methods such as setLabel(), rather than relying on the legacy method presented in this article. I’ve posted an update to this article.

  33. Chandra July 21, 2017 at 6:36 am - Reply

    Great Solution Mark! Thanks for your post on this!! Worked like a charm! Very helpful!

Leave A Comment