CRM 2011: JavaScript – An Assortment of JavaScript Code Snippets

When we are working with JavaScript in a CRM form, we must first work out which section of the form we want to reference.

Once that has been decided we have a variety of commands we can use.

I have already covered how to obtain a value from a lookup field and how to get the FormType in earlier posts so I will not repeat them here.

Below is some Javascript code snippets I frequently use on a day-to-day basis which i thought i would share here.

Note: All references to “fieldName”, “tabName” and “sectionName” refer to the Schema Names of the Field/Tab/Section and not their Display Names.

Getting a field value


Setting a field value


Clearing a field value


Getting a picklist’s option text

//Note: The previous get/set commands will also work fine with picklists
//Although when setting a value, we set the numeric value not the text value

Setting the requirement level of a field


Enable/Disable a field

Xrm.Page.ui.controls.get("fieldName").setDisabled(false); //Enabled
Xrm.Page.ui.controls.get("fieldName").setDisabled(true); //Disabled

Setting a field’s visibility

Xrm.Page.ui.controls.get("fieldName").setVisible(true); //visible
Xrm.Page.ui.controls.get("fieldName").setVisible(false); //not visible

Setting a tab’s visibility

Xrm.Page.ui.tabs.get("tabname").setVisible(true); //visible
Xrm.Page.ui.tabs.get("tabname").setVisible(false); //not visible

Xrm.Page.ui.tabs.get("tabName").setVisible(true); //visible
Xrm.Page.ui.tabs.get("tabName").setVisible(false); //not visible

Setting a section’s visibility


//not visible

Get the Guid of the current record;