OnChange script not working as intended

Staxed
Giga Guru

I'm having a difficult time getting this script to do what I want it to do.  It should be looking at the Division (newValue) and then depending on that, clear all options in location and populate with a specific set for each Division.

If I use the script as written below, whenever the form loads, it changes the location field to whatever the first option in the list is.

If I change the first if in the function to (isLoading || newValue === ' '), it then works as intended and doesn't change the location field itself, but it also shows every location for every division instead of just the appropriate locations.  I'm not sure what I'm missing here.

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

	if(newValue=='Charleston')
	{
		g_form.clearOptions('u_hr_location', 'Location');
		g_form.addOption('u_hr_location','Charleston','Charleston');
		g_form.addOption('u_hr_location','Charleston MCP','Charleston MCP');
	}
	
	else if(newValue=='Florence')
	{
		g_form.clearOptions('u_hr_location', 'Location');
		g_form.addOption('u_hr_location','Florence','Florence');
		g_form.addOption('u_hr_location','Florence MCP','Florence MCP');
		g_form.addOption('u_hr_location','Marion','Marion');
		g_form.addOption('u_hr_location','Marion MCP','Marion MCP');
	}
	
	else if(newValue=='Lancaster')
	{
		g_form.clearOptions('u_hr_location', 'Location');
		g_form.addOption('u_hr_location','Chester','Chester');
		g_form.addOption('u_hr_location','Lancaster','Lancaster');
		g_form.addOption('u_hr_location','Lancaster MCP','Lancaster MCP');
	}
	
	else if(newValue=='Midlands')
	{
		g_form.clearOptions('u_hr_location', 'Location');
		g_form.addOption('u_hr_location','Columbia','Columbia');
		g_form.addOption('u_hr_location','Kershaw','Kershaw');
		g_form.addOption('u_hr_location','Midlands MCP','Midlands MCP');
	}
   
}
1 ACCEPTED SOLUTION

ProcessMatters
Giga Guru

You will need an onLoad script to perform essentially the same functionality, as onChange will only fire when the value changes.

View solution in original post

20 REPLIES 20

DanielCordick
Mega Patron
Mega Patron
Have you taken a look at this? May help https://servicenowguru.com/scripting/client-scripts-scripting/removing-disabling-choice-list-options/ Please mark helpful or correct 🙂