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.
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…
//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…
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…
If I wanted to change the label to a bold green color I could do it like this…
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…
//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){};
}
This is great! Thanks!
Is it possible to change the table label using something similar?
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 newLabel = 'Changed Incident Label';
var labelEl = $$('.form_header')[0];
var newHTML = labelEl.innerHTML.replace(currentLabel, newLabel);
labelEl.innerHTML = newHTML;
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?
Is there a way to do the same thing with a catalog item – record producer for a variable?!
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.
Nice work!, What does the $ & $$ means in above script?
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/
Mark,
Thanks for your reply. Ive just figured it out with some hints from your other post.
Care to post your script here? That would be a nice one to have.
With pleasure,
Here it is:
// 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';
}
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!
Thank you very much for this!
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!
SNnoobie, this should help.
// 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;
}
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?
Mark, any chance something like this could be done to a change the name of a list view column header?
Hey Steve,
There’s no good way that I know of to do this. Client scripts cannot be run from a list view.
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
Hi Mark,
Is it possible to change Field Label in List Layout?
That’s not possible currently.
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
I think form annotations are probably the best option on a standard form.
https://wiki.servicenow.com/index.php?title=Annotating_Forms
Can anyone explain the functionality of the above code plzz…
labelElement.select(‘label’).each(function(elmt) {
elmt.innerHTML = label + ‘:’;
});
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.
To change the hint (on hover text):
var fieldFormName = g_form.getTableName() + "." + field;
var fieldLabelName = "label." + fieldFormName;
try{
var labelElement = $(fieldLabelName);
labelElement.title = newtitle;
}catch(e){
alert("Error:" + e)
};
}
Thanks Gary!
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?
//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){};
}
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
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"});
}
Looks like you’re combining what we’ve got here with an out-of-box script. This should work better…
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){};
}
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.
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’);
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.
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”?
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.
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!
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.
Thanks for checking into it I really appreciate you taking time to look at it.
Have a great day!
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?
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.
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
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;
Thank you Mark, that did the trick
S
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
Worked Perfect…….
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.
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.
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?
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.
Thanks Mark! That might just do the job..
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.
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.
//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){};
}
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.
Only thing I can think of that might work is just to replace the label text with label text in ‘‘ bold tags.
Mark,
I need to underline my text as well. How would I do that?
Thanks!
Tina,
I have made a few adjustments to Mark’s UI Script to achieve the underlined text.
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’)
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!
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.
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)
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.
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.
Hi Kumarr,
Your question is outside the scope of this article. We recommend that you post it on the ServiceNow Community Forum.
This script not working in Istanbul release
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.
It is not working in Service Portal. Is it a known issue or I have to do something else
Hi Pallabi,
This solution is not compatible with the Service Portal. You should use the new Mobile GlideForm API to change labels instead.
Mark,
Script works great in the ITIL view of ServiceNow, but doesn’t work in the Service Portal. Any fixes for that?
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.
Great Solution Mark! Thanks for your post on this!! Worked like a charm! Very helpful!