---
sourceDocument: Brazil API Reference
sourceDocumentLink: https://www.servicenow.com/docs/r/api-reference

 Release :

    - brazil

ft:locale :

    - en-US

ft:publication_title :

    - Brazil API Reference

ft:clusterId :

    - crapiref

bundleId :

    - crapiref

workflow :

    - Creator


---

# Field script use cases

# Field script use cases {#ariaid-title1}

Release version: Brazil  
Updated September 10, 2026  
![](https://www.servicenow.com/docs/portal-asset/ico-clock) 4 minutes to read
Summarize  
![AI sparkle icon](https://servicenow.com/docs/portal-asset/ai-sparkle-icon) Summarized using AI  
This content was generated using new OpenAI-powered functionality. Results are provided on an as is basis and are not guaranteed to be accurate or complete.  

## Summary of Field script use cases

This document provides practical examples of client-side and server-side scripts used to customize field behavior in ServiceNow.
These scripts enhance user experience and data integrity by automating field population, modifying field appearance, enforcing data format, and managing date/time values.
The examples serve as reference implementations that require thorough testing and are not officially supported by Now Support.
Show full answer Show less  

## Common Use Cases and Practical Implementations

* **Automatically Populate a Field:** A client script that automatically fills the *Short Description* field based on the selected *Subcategory* in the Incident form. It queries a lookup table and sets the short description accordingly, improving data consistency and reducing manual entry.
* **Disable HTML Tags in Descriptions:** A server-side script that sanitizes the *Description* and *Short Description* fields by replacing HTML script tags with non-executing text, enhancing security by preventing script injection.
* **Eliminate Leading and Trailing Spaces:** A server script that trims whitespace from *FirstName* and *LastName* fields on the *sysuser* table, ensuring clean user data.
* **Make a Field Label Flash:** A client script that causes a field label (e.g., Incident number) to flash with a specified color and duration, useful for drawing user attention.
* **Make a Field Label Bold:** A client script that sets the font weight of a field label (e.g., Short Description) to bold, enhancing visual emphasis.
* **Make Fields Read-Only:** A client onLoad script that sets multiple fields (Incident state, Impact, Urgency, Priority, Configuration item, Assigned to) to read-only based on incident state, including disabling reference field lookups by removing their magnifying glass icons.
* **Set Current Date/Time in Fields:** Demonstrates how to set current date and time values in fields using GlideAjax and a server-side Script Include, ensuring proper time zone formatting and seamless client-server interaction.
* **Toggle Timer Field by Field Name:** A client script that programmatically starts or stops a timer control associated with a specific field by simulating user interaction, useful for tracking time-based activities.
* **Modify GlideDateTime Field Values:** Server-side examples showing how to manipulate date/time fields using the GlideDateTime API, including adding or subtracting seconds, days, weeks, months, or years, and setting display values with time zone consideration.

## Practical Benefits for ServiceNow Customers

* Automate repetitive data entry tasks, reducing errors and improving efficiency.
* Enhance data quality by enforcing formatting rules and sanitizing input.
* Improve user interface by visually emphasizing important fields.
* Control field accessibility dynamically based on form state to prevent unwanted changes.
* Handle complex date/time manipulations accurately respecting user time zones.
* Enable advanced user interactions such as timer toggling for time tracking purposes.

## Important Notes

* All scripts are example templates and must be adapted and tested thoroughly in your instance before deployment.
* These customizations are provided as-is and are not officially supported by Now Support.
* For server-side code invoking client scripts, GlideAjax is demonstrated as the preferred approach for client-server communication.  
Common use cases for field customization scripts.
Warning:  
The customization described here was developed for use in specific instances, and is not supported by Now Support. This method is provided as-is and should be tested thoroughly before implementation. Post all questions and comments regarding this customization to our community [forum](http://community.service-now.com/).

For more information, see [Server API reference](https://www.servicenow.com/docs/iOT1N0LGPaVO16cusc_QWg "Use server APIs in scripts to change the functionality of applications, or when you create new applications.").

## Automatically populate a field {#r_UsefulFieldScripts__section_upr_nvx_mtb}

The following example shows how to use a client script to auto-fill a Short Description based on the selected Subcategory.

In this case, if the table has a record with Subcategory = Password
and Short Description = Password Reset. When the user selects the
Subcategory of Password on the Incident
form, a client script looks up the matching record and sets Short Description equal to Password Reset.  
Client script settings:

* Type = onChange
* Table name = incident
* Field name = Subcategory

{#r_UsefulFieldScripts__ul_ix3_hyx_mtb}

    function onChange(control, oldValue, newValue, isLoading){
        if(isLoading){return;}
        var newrec = gel('sys_row');
        //Check if new record
        if (newrec.value == -1) {
            var lookup = new GlideRecord('u_short_desc_lookup');
            lookup.addQuery('u_subcategory', g_form.getValue('subcategory'));
            lookup.query();
            var temp; //temp var - reusable
            if(lookup.next()){
                temp = lookup.u_short_description;
                if(null != temp) {
                    //Set the form value from lookup if there is a lookup value
                    g_form.setValue('short_description', temp);
                } else {
                    g_form.setValue('short_description',"");
                    }
              } else {
                  //If a lookup record does not exist based on lookup.addQuery
                  //Then set to UNDEFINED or NULL depending on type
                  g_form.setValue('short_description',"");
                  }
         }
    }

## Disable HTML tags in descriptions {#r_UsefulFieldScripts__section_o2z_kxx_mtb}

This code disables HTML tags in Description and Short Description fields by substituting the tags with non-executing versions.

    doit();
     
    function doit(){ 
     var desc = current.description.toString();
     var shdesc = current.short_description.toString();
     if(desc.indexOf('script>')>-1|| shdesc.indexOf('script>')>-1){
       desc = desc.replace(/<script>/g,"(script)");
       current.description = desc.replace(/<\/script>/g,"(\/script)");
       shdesc = shdesc.replace(/<script>/g,"(script)");
       current.short_description = shdesc.replace(/<\/script>/g,"(\/script)");}
    }

## Eliminate leading and trailing spaces in fields {#r_UsefulFieldScripts__section_kbd_gxx_mtb}

This example of the script trims trailing and leading spaces in the FirstName and LastName fields of the sys_user.

    doit();
     
    function doit(){ 
      var now_GR =new GlideRecord('sys_user');
      gr.query();
      while(gr.next()){
        if((gr.first_name.toString().length!= gr.first_name.toString().trim().length)||(gr.last_name.toString().length!= gr.last_name.toString().trim().length)){
         gr.first_name= gr.first_name.toString().trim();
         gr.last_name= gr.last_name.toString().trim();
         gr.autoSysFields(false);
         gr.update();}}
    }

## Make a field label flash {#r_UsefulFieldScripts__section_lnv_swx_mtb}

The following client script example is for the number field on incident. The label flashes for two seconds.

    g_form.flash("incident.number","#FFFACD",0);

The arguments for the flash method are as follows:

* tablename.fieldname
* RGB color or acceptable CSS color like "blue" or "tomato"
* Integer that determines how long the label flashes:
  * 2 for a 1-second flash
  * 0 for a 2-second flash
  * -2 for a 3-second flash
  * -4 for a 4-second flash
  {#r_UsefulFieldScripts__ul_xky_hdr_4x}
{#r_UsefulFieldScripts__ul_qh5_kgr_4x}  
Note:  
Do not specify this argument if you want the field label colored the specified color.

## Make a field label bold {#r_UsefulFieldScripts__section_y4k_xwx_mtb}

This client script makes the label of a particular field bold. In this case, the field is the Short Description on the Incident Table.

    function onLoad(){
      var l = g_form.getLabel('incident.short_description');
      l.style.fontWeight = 'bold';}

## Make fields read-only {#r_UsefulFieldScripts__section_bhw_4vx_mtb}

This onLoad client script makes the following fields on the Incident \[incident\] table read-only:

* Incident state
* Impact
* Urgency
* Priority
* Configuration item
* Assigned to
{#r_UsefulFieldScripts__ul_pbz_tzx_mtb}  
The script also removes the magnifying glass for the read-only Reference Fields (Configuration item and Assigned to).

    function onLoad(){
    var incidentState = g_form.getValue('incident_state');
    if( incidentState == '6'|| incidentState == '7'){
       g_form.setReadonly('incident_state',true);
       g_form.setReadonly('impact',true);
       g_form.setReadonly('urgency',true);
       g_form.setReadonly('priority',true);
       g_form.setReadonly('cmdb_ci',true);
       g_form.setReadonly('assigned_to',true);}}

## Set current date/time in field {#r_UsefulFieldScripts__section_vpr_nvx_mtb}

You can set date and time values in client scripts and script includes.

Client script
:   You can use the following two lines to set the current date and time in a date/time field. This approach bypasses the problem of getting the value into the proper format and proper time
    zone.

        var ajax = new GlideAjax('MyDateTimeAjax');
          ajax.addParam('sysparm_name','nowDateTime');
          ajax.getXML(function(){
            g_form.setValue('put your field name here', ajax.getAnswer());});

:   For more information on running server-side scripts with the client, refer to [GlideAjax](https://www.servicenow.com/docs/h1cWBrEDdpRzWDHeK~DszA#p_AJAX "AJAX (asynchronous JavaScript and XML) is a group of interrelated, client-side development techniques used to create asynchronous Web applications.").

System script include
:

        // Be sure the Glide AJAX enabled option is checked
         
        var MyDateTimeAjax = Class.create();
        MyDateTimeAjax.prototype = Object.extendsObject(AbstractAjaxProcessor,{
          nowDateTime:function(){
            return gs.nowDateTime();}});

## Toggle the timer field by field name {#r_UsefulFieldScripts__section_xzg_mvx_mtb}

The following client script toggles the timer field based on a particular field name.

    function toggleTimerByFieldName(fieldName){
     //Step 1: Find the timer object
     //timeObjectName: the timer objects name as it would normally be referenced
     //timeObjectHidden: the hidden input node in the field td
     //timeObjectParent: the parent td node containing the field and it's constituent nodes
     //timeObjectFields: anchor tag with onclick to stop timer
     
     var timeObjectName = fieldName;
     var timeObjectHidden = gel(timeObjectName);
     
     //Step 2: simulate click stop button
     var timeObjectParent;
     var timeObjectFields;
     
     //verify that we got the correct object
     if(timeObjectHidden.type=="hidden"){
     
        //Get Parent td node
        timeObjectParent = timeObjectHidden.parentNode;
     
        //Get input fields
        timeObjectFields = timeObjectParent.getElementsByTagName("input");
     
        //simulate click of stop button
        var timerTestString ="paused";
        var timerImg;
     
        //loop through input objects looking for the pause timer object
        for(var elIt=0; elIt < timeObjectFields.length; elIt++){
          if(timeObjectFields[elIt].id.match(timerTestString)){
            if(timeObjectFields[elIt].value=="false"){
              timeObjectFields[elIt].value="true";
              timerImg = timeObjectParent.getElementsByTagName("img")[0];
              timerImg.src="images/timer_start.gifx";}
          elseif(timeObjectFields[elIt].value=="true"){
              timeObjectFields[elIt].value="false";
              timerImg = timeObjectParent.getElementsByTagName("img")[0];
              timerImg.src="images/timer_stop.gifx";}}}}}

## Modify GlideDateTime field values {#r_UsefulFieldScripts__section_mod-gdt-fields}

The following server-side script example shows how to modify values using the GlideDateTime API. The same concept also applies to the GlideDate object.  
Note:  
The following script is only intended for global applications.

    //You first need a GlideDateTime object
    //this can be from instantiating a new object "var gdt = new GlideDateTime()"
    //or getting the object from a GlideDateTime field
    //getting the field value (for example: var gdt = current.start_date) only returns the string value, not the object
    //to get the object use var gdt = current.start_date.getGlideObject(); (GlideElement)
    //now gdt is a GlideDateTime object
    var gdt = current.start_date.getGlideObject();
     
    //All methods can use negative values to subtract intervals
     
    //add 1 hour (60 mins * 60 secs)
    gdt.addSeconds(3600);
     
    //add 1 day
    gdt.addDaysLocalTime(1);
     
    //subtract 1 day
    gdt.addDaysLocalTime(-1);
     
    //add 3 weeks
    gdt.addWeeksLocalTime(3);
     
    //subtract 6 months
    gdt.addMonthsLocalTime(-6);
     
    //add 1 year, representing the date and time using the UTC timezone instead of the local user's timezone.
    gdt.addYearsUTC(1);
     
    //set the value of the GlideDateTime object to the current session timezone/format
    GlideSession.get().setTimeZoneName('US/Eastern');
    gdt.setDisplayValue('2018-2-28 00:00:00');
    gs.info('In ' + GlideSession.get().getTimeZoneName() + ": " + gdt.getDisplayValue());

See also:

* [Manipulate date and time values](https://www.servicenow.com/docs/T16C7mU7BHGDoHJDPxeUKg#c_GlideDateTime "The GlideDateTime class provides methods for performing operations on GlideDateTime objects, such as instantiating GlideDateTime objects or working with glide_date_time fields.")
* [GlideDate - Global](https://www.servicenow.com/docs/~iHrWviBNdbLmka3DJTAJA#GlideDateAPI "The GlideDate class provides methods for performing operations on GlideDate objects, such as instantiating GlideDate objects or working with GlideDate fields.")
* [GlideDate - Scoped](https://www.servicenow.com/docs/3k5kGlXFrKQChqjUZteCoA#c_GlideDateScopedAPI "The scoped GlideDate class provides methods for performing operations on GlideDate objects, such as instantiating GlideDate objects or working with GlideDate fields.")
* [GlideDateTime - Global](https://www.servicenow.com/docs/NXt_5lV~X8TiR60g83anow#c_GlideDateTimeAPI "The GlideDateTime class provides methods for performing operations on GlideDateTime objects.")
* [GlideDateTime - Scoped](https://www.servicenow.com/docs/qlqnGUWQdqMziBfEP_ciVA#c_GlideDateTimeScoped "The scoped GlideDateTime class provides methods for performing operations on GlideDateTime objects.")
* [GlideElement - Global](https://www.servicenow.com/docs/u7r_zxuGxGzfCIHtB7dM4A#c_GlideElementAPI "The GlideElement API provides a number of convenient script methods for dealing with fields and their values. GlideElement methods are available for the fields of the current glide record.")
* [GlideElement - Scoped](https://www.servicenow.com/docs/C8CC406WvuFk2YikeqnlpA#c_GlideElementScopedAPI "The scoped GlideElement API provides a number of convenient script methods for dealing with fields and their values. Scoped GlideElement methods are available for the fields of the current glide record.")
* [GlideTime - Scoped](https://www.servicenow.com/docs/9HyNOhJnSDGHFNIOE743dg#c_GlideTimeScopedAPI "The GlideTime API provides methods for performing operations on GlideTime objects, such as instantiating GlideTime objects or working with GlideTime fields.")
{#r_UsefulFieldScripts__ul_l51_1xl_cjc}
* **[Approval assignment scripts](https://www.servicenow.com/docs/IKt3ZjVFWHN0XGfFQHopcw)**   
  This is a searchable version of the useful approval and assignment scripts.

