Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

onChange Client Script setValue

jmichael
Kilo Contributor

onChange script not working. Needs to set two fields bases off of a reference field selection. Base field value is selected from the reference the description then needs to populate of that item and the type of item. The description field is a normal string field and the type is a choice field. These can both be set without a Script Include, but its not working. I'm sure its a problem with the script.

How should the syntax look for this?

1 REPLY 1

Anthony_vickery
Tera Expert

If I've read and understood your question...You have a (assume custom) table that holds a "u_description" string field and a "u_type" choice field. Your form (assume change_request) has a reference field to this (custom) table and onchange of this reference, you want to populate the description and type fields of the current (change_request) form. I also go further to assume that the option for the choice field is readily available and does not need to be added dynamically.


//On change of the reference field to the (custom) table



function onChange(control, oldValue, newValue, isLoading) {


//If the form is loading, do nothing


    if (isLoading)


          return;



//If the description and type fields are not on the form, do nothing


//---assuming these fields are OOB, hence are not prefixed with u_


    if (!g_form.getControl('description') && !g_form.getControl('type'))


          return;



//If the reference field was cleared, clear the description and type fields


    if (newValue == '') {


          setMyFields();


          return;


    }



//If we got this far,


//-the form is not loading,


//-the other fields are on the form


//-the reference field has a value


//time to make a server call



//control.id.split('.')[1] is just a shortcut to the name of the field triggering this onchange script


    g_form.getReference(control.id.split('.')[1], setMyFields);


}



//This function will either set or clear the field values


function setMyFields(serverRecord) {


            var myDesc = (!serverRecord) ? '' : serverRecord.u_description; //u_description is a string field of the (custom) table


            var myType = (!serverRecord) ? '' : serverRecord.u_type; //u_type is a choice field, so this needs to be the choice value, not the display value


            //---assuming these fields are OOB, hence are not prefixed with u_


            g_form.setValue('description', myDesc);


            g_form.setValue('type', myType);


}