Onload Client Script in servicenow

0
1983

Client-side scripts execute within a user’s browser and are used to manage forms and form fields. Examples of things client-side scripts can do include:

      • Place the cursor in a form field on form load
      • Generate alerts, confirmations, and messages
      • Populate a form field in response to another field’s value
      • Highlight a form field
      • Validate form data
      • Modify choice list options
      • Hide/Show fields or sections

How Onload client script works?

      • Onload client script will execute once forms are loaded.
      • Script will get executed when the system first renders the form and before users can input the data.
      • Its been used when you want to change something on the form while it is loading.
      • Typically, onLoad()client scripts perform client-side-manipulation of the current form or set default record values.
      • Default code that system provides after select client script type as onload.
        function onLoad() {
           //Type appropriate comment here, and begin script below
           
        }

         

I have explained the above pic in details in the video. Request you to watch it for better understanding.

 

Now lets take a look on real word example

Real World Scenario

Requirement: Hide “Closed” Incident state and State from everyone accept user who has itil_admin role.

Solution: create onload client script and write below code.

function onload() {
    if (g_user.hasrole('itil_admin'))
        return;

    if (g_form.getvalue('incident_state') != '7')
        g_form.removeoption('incident_state', 7);
    if (g_form.getvalue('state') != '7')
        g_form.removeoption('state', 7);
}

 

Q. How can we change onChange client script into onLoad?

Ans: You need to do one simple change in if condition, just remove the “isLoading ||”

    • Default code for onchange
      function onChange(control, oldValue, newValue, isLoading, isTemplate) {
         if (isLoading || newValue === '') {
            return;
         }
      
         //Type appropriate comment here, and begin script below
         
      }
    • After removing “isLoading ||”, your base code looks like.
      function onChange(control, oldValue, newValue, isLoading, isTemplate) {
         if (newValue === '') {
            return;
         }
      
         //Type appropriate comment here, and begin script below
         
      }

 

You can not call event from client side, Event will be call on server side only but you can call event in UI action.
Q. Which is executed first UI or client script?
UI Policies execute after Client Scripts. If there is conflicting logic between a Client Script and a UI Policy, the UI Policy logic applies.

 

 

Get Latest Update From Runjay Patel

We don’t spam! Read our privacy policy for more info.

LEAVE A REPLY

Please enter your comment!
Please enter your name here