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.

Auto select the choice field depending on the value of other choice field

rohitservicenow
Mega Guru

Hello,

I am pretty new to ServiceNow need help with the sample code to auto select a choice field based on the choices selected in another field.

Suppose, I have two custom fields, A and B

A has some 50 choices and B has 10. Based on the choices selected on A, I want to auto populate the B's values.

Can we write the OnChange script / Bus rule?

Thanks,

Rohit

1 ACCEPTED SOLUTION

Please try in this way then, make sure different arrays do not have same values.



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


    if (isLoading || newValue === '') {


          return;


    }


var arrayA1 = [1, 10, 15, 20, 24, 25];


var arrayA2 = [2, 6, 7, 8, 38, 49];


    //Type appropriate comment here, and begin script below


if(arrayA1.includes(parseInt(g_form.getValue('field_A'))))


g_form.setValue('field_B', '60');


if(arrayA2.includes(parseInt(g_form.getValue('field_A'))))


g_form.setValue('field_B', '70');


}


View solution in original post

19 REPLIES 19

If i understand clearly then you want to set the field B value to 60 if field A has any value in between 1 to 50, and both the fields are choice fields, then let's try in this way with onChange() client script, see if this helps.



var fieldA = g_form.getValue('field_A');


if(parseInt(fieldA) > 1 && parseInt(fieldA) <= 50)


g_form.addOption('field_B', '60', '60');


else


g_form.clearValue('u_description');


not any value between 1 and 50, but only some values between 1 and 50. let's say if the value of A is any one of 1, 10, 15, 20, 24, 25 then, set B value as 60. and A value is again any of 2, 6, 7, 10, 38, 49, then populate B value as 70.



Thanks for the help.


Please try in this way then, make sure different arrays do not have same values.



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


    if (isLoading || newValue === '') {


          return;


    }


var arrayA1 = [1, 10, 15, 20, 24, 25];


var arrayA2 = [2, 6, 7, 8, 38, 49];


    //Type appropriate comment here, and begin script below


if(arrayA1.includes(parseInt(g_form.getValue('field_A'))))


g_form.setValue('field_B', '60');


if(arrayA2.includes(parseInt(g_form.getValue('field_A'))))


g_form.setValue('field_B', '70');


}


Thank you, this is what I have been looking for. Thank you so much!


Hi Shishir,


If I have to use the same code on before business rule, what are the changes i need to make please