How to hide/show fields based on Choice list in OnChange Client Script using Arrays!!!

Jaichand
Kilo Contributor

I arranged fields in a form. Based on the choice list, the appropriate fields should be hidden/shown.

1 ACCEPTED SOLUTION

asifnoor
Kilo Patron

Hello Jaichand,

You can do this with UI policy and client script. But if the no. of fields are more and varies based on choice fields, then it can become a lengthy script. 

You can make it dynamic like this.

function onChange(control, oldValue, newValue, isLoading, isTemplate) {
	if (isLoading) {
		return;
	}
	//make an array of all fields that need to be hidden or shown.
	var all_fields = "subcategory,business_service,cmdb_ci,assignment_group,assigned_to";
	//Then make a key value of choice value and its associated fields to be hide.
	var fields = {};
	fields.software = "subcategory,business_service";
	fields.hardware = "cmdb_ci";
	fields.network = "subcategory,business_service,cmdb_ci";
	fields.database = "assignment_group,assigned_to";
	//On selection of any choice, first make all fields invisible.
	if(newValue!='') {
	        all_fields = all_fields.split(",");
		for(i=0;i<all_fields.length;i++) {
		        //g_form.setDisplay(all_fields[i],false);
			g_form.setVisible(all_fields[i],false);
		}
		//now show only those fields which are linked to the choice
		for(var key in fields) {
		        if(key == newValue) {
			        var linked_fields = fields[key].toString();
				alert(linked_fields);
				linked_fields=linked_fields.split(",");
				for(i=0;i<linked_fields.length;i++) {
				        //g_form.setDisplay(linked_fields[i],true);
					g_form.setVisible(linked_fields[i],true);
				}
			}
		}
	} else {
                //if selection of choice is set to none
	        all_fields = all_fields.split(",");
		for(i=0;i<all_fields.length;i++) {
		        //g_form.setDisplay(all_fields[i],true);
			g_form.setVisible(all_fields[i],true);
		}
	}		
}

Kindly mark the comment as a correct answer and helpful if it helps to solve your problem.

Regards,
Asif
2020 ServiceNow Community MVP

View solution in original post

7 REPLIES 7

Thank you  Gaurav

hello gaurav ,

 

I have similar requirement where i have choice list value as walkin which should not be visble on incident form but when done form submitted through portal the value should be set to walkin directly , Plz help

adnanzahid
Tera Contributor

Hello Gaurav,

 

Is this approach applicable to a catalog form?