Client Script to auto populate field based on another field not working

User393503
Tera Expert
I want to display the 'parent' value in the 'project' field based on the budget. I tried a getReference and that kept returning the sys id. How do I return the value correctly using displayBox method or getDisplayValue?
 
 
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    var budget1 = g_form.getDisplayBox('parent').value;
   


 
   
g_form.setValue('project', budget1.parent);
7 REPLIES 7

@User393503 

you will have to use GlideAjax as you cannot dot walk 2 levels in client script

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

Community Alums
Not applicable

Hi @User393503 ,

I tried your problem in my PDI it works for me please refer below solution 

Client script

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    //Type appropriate comment here, and begin script below
	var budget1 = g_form.getValue('parent');

    var ga = new GlideAjax('AutoPopulate_CallerInfo');
    ga.addParam('sysparm_name', 'getCallerInfo');
    ga.addParam('sysparm_value', budget1);

    ga.getXML(callback);

    function callback(response) {
        var answer = response.responseXML.documentElement.getAttribute("answer");
        alert('Name = ' + answer);
    }
}

 

Create Script Include which is client callable and below code 

 

getCallerInfo: function() {

    var ids = this.getParameter('sysparm_selectedIds');
    gs.log("sysparm_selectedIds" + ids);
    var incGr = new GlideRecord('yourTable');
    incGr.addQuery('parent', ids); //<your query>
    incGr.query();
    if (incGr.next()) {
        var name = incGr.getDisplayValue("fieldBackendName");
        return name
    }
}

 

 

Please mark my answer correct and helpful if this works for you

Thanks and Regards 

Sarthak

swathisarang98
Giga Sage
Giga Sage

Hi @User393503 ,

 

You can achieve this through getReference method and dot walking,

Please check the below example which gives me alert of the caller if changed, in your case you can add setvalue instead of alert.

swathisarang98_0-1718718096247.png

 

 

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
    if (isLoading || newValue === '') {
        return;
    }

    var caller = g_form.getReference('caller_id', currentUser1); // add your reference field here

    function currentUser1(caller) {
        alert(caller.name); // i have added alert for testing instaed of this you can set value based your requirement.
    }
}

 

Please mark this comment as Correct Answer/Helpful if it helped you.

Regards,

Swathi Sarang