call a client script within another client script

rody-bjerke
Giga Guru

Hi,

Is it possible to call a client script within another client script?

Let's say you have alot of code, and you want it to run OnLoad, so you create a client script OnLoad with the code.

Then you also want the same code to run OnChange when the field CI changes, then you could make 2 client scripts, one OnLoad and one OnChange with the same code. But, could you for example connect these two, so you have one client script with the code, and another client script simply just calling the first one.

Best regards,

13 REPLIES 13

Alikutty A
Tera Sage

Hi Rody,



Yes this is possible, you can add all reusable code as function in your onLoad client script and call them in onChange() or onSubmit() client scripts. The scope of variables and functions inside onLoad client script is valid until you close the form. The same applies when you use a scratchpad on display business rule. If you declare a scratchpad variable then it is accessible across all client scripts.



Thanks


Please Hit like, Helpful or Correct depending on the impact of the response


Hi Alikutty,



A client script starts with:



function onLoad() {


    //Type appropriate comment here, and begin script below



Would that be something like "function onLoad(reusable_code)" where "reusable_code" is the name of a client script.


Or would that only be "onChange(reusable_code)" to call it.


HI Rody,



I suggest to consider using UI Scripts to store your reusable code:


UI scripts



Andras


Hi Rody,



The script within you onLoad will have other functions of the reusable code, something like this :


<code>


function onLoad(){


//onLoad code


}


function doThisWork(ifAnyParams){


//doThisWork code


}


function doThatWork(varifAnyOtherParams){


//doThatWork code


}


</code>



and you onChange function can simply call them, something like this :



<code>


function onChange(){


//onChange code


//call doThisWork


var returnedValue = doThisWork(ifAnyParams); //pass if any Params


//remaining onChange code


}


</code>



Also you can use UI Scripts - ServiceNow Wiki   , if the code is being reused a lot.


Hope this helps.