JavaScript – Set optionset values by name

A simple but hopefully useful JavaScript function. Pass the name of an option set (pick list) and text value to set the value based on the text.

For example;

SetOptionSet(“new_country”, “England”);

// *** FUNCTION: SetOptionSet
// *** PARAMS:
// ***  fieldName = The name of the optionset field
// ***  setText = The text to set the optionset with
function SetOptionSet(fieldName, setText) {
	try {
		var control = Xrm.Page.getAttribute(fieldName);

		if (control.getAttributeType() == 'optionset') {
			if (setText == "" || setText == null || setText == undefined) {
				control.setValue(null);
			}
			else {
				var controlOpts = control.getOptions();
				for (var i = 0; i <= controlOpts.length - 1; i++) {
					if (controlOpts[i].text.toLowerCase() == setText.toLowerCase()) {
						control.setValue(controlOpts[i].value);
						return ;
					}
				}
			}
		}
		else {
			alert("Invalid field type or field not found. Field type should be OptionSet");
			return ;
		}
	}
	catch (e) {
		alert("Error in SetOptionSet: fieldName = " + fieldName + " setText = " + setText + " error = " + e);
	}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s