Below are the few useful properties, commands in ms crm 2011 ms crm 2013 and ms crm 2015 Javascript. You can work with them on form event say OnLoad.

Click on the item below to go through the description about that.
  • Get the string value of a Text field
  • Set the string value of a Text field
  • Retrieve Optionset Value/Text
  • Get the label name of the field
  • Get Lookup field name(value)
  • Get Lookup field ID
  • Get current entity name
  • Get Type Code of lookup
  • Get reference entity name of lookup
  • Set Lookup field
  • Get Event generated field value
  • Get Organization Name
  • Get Organization Language Code
  • Get Server URL
  • Check for Dirty
  • Get GUID of current record
  • Whether the field is disabled or not
  • Get form type
  • Get required fields in the form
  • Save the current record
  • Save the current record
  • Set focus on the field
  • Hide a field on the form
  • Disable(Read only) and Enable a field
  • Close opened window
  • Open Browser Window
  • Get Logged-in User ID
  • Attach Event to control
  • Set Description field in E-mail entity
  • Set IFrame URL
  • Get Schema Names of the Attributes
  • Get Teams of User
  • Filtered Lookup
  • Trigger the Workflow
  • Set field value using query string parameter
  • Change the Status and Status Reason of the record
  • Get the current form name
  • Refresh the form
  • Hide left navigation item
  • Set field requirement level in run time
  • Get Organization URL

Get the string value of a Text field:

Returns the string value in the text field.
var fieldValue ="fieldName").getValue();

Set the string value of a Text field:

Set the string value for Text field."fieldName").setValue("New Value");

Retrieve Optionset Value/Text:

Returns the Value/Text of Optionset.
var optionSet ="optionSetName");
var optionSetText = optionSet.getText();
var optionSetValue = optionSet.getValue();

Get the label name of the field:

Get the Label of the specified field.
var fieldLabel = Xrm.Page.ui.controls.get("fieldName").getLabel();

Get the Lookup field value:

Get the value in given Lookup field.

Get the Lookup field ID:

Returns the ID of the record to which the lookup pointing to.

Get current entity name:

Returns the logical name of the current entity.
var entityName =;

Get Type Code of lookup:

Returns the code type with respect to an entity the lookup pointing to.
var objectTypeCode = Xrm.Page.getAttribute("lookupFieldName").getValue()[0].type;

Get reference entity name of lookup:

Returns the logical name of an entity the lookup pointing to.
var entityName = Xrm.Page.getAttribute("lookupField").getValue()[0].entityType;

Check for Dirty:

Returns a Boolean value indicating if any fields in the form have been modified.
var formChanged =;

Set Lookup field:

Set the lookup field value.
var lookupValue = new Array();
lookupValue[0] = new Object();
lookupValue[0].id = newId;
lookupValue[0].name = newName;
lookupValue[0].entityType = entityType;

Get event generated field value:

Returns the value of the field which generates the event.

function fieldValue_onchange(obj) {
  var attribute = obj.getEventSource();
  alert(attribute .getValue());

Get Organization Name:

Returns the unique name of logged-in organization.
var orgName = Xrm.Page.context.getOrgUniqueName();

Get Organization Language Code:

Returns organization's language code(LCID).
var orgLanguage = Xrm.Page.context.getUserLcid();

Get Server URL:

Returns the base server URL.
var orgName = Xrm.Page.context.getServerUrl();

Get GUID of current record:

Returns GUID for the record.
var guid =;

Whether the field is disabled or not:

Returns a Boolean value indicating whether the control is disabled.
var fieldDisabled = Xrm.Page.ui.controls.get("fieldName").getDisabled();

Get form type:

Returns an integer value, indicates the form type: 1-Create, 2-Update
var FormType = Xrm.Page.ui.getFormType();

Get required fields in the form:

Returns required field names in the form: function (attribute, index) { 
 if (attribute.getRequiredLevel() == "required" ) {
  requiredFields += attribute.getName()+"\n";
} );

Form Save:

Save the current form.;

Form Save and Close:

Save and Close the form."saveandclose");

Set Focus:

Set focus on the control.

Hide a field:

Hide the specified control.

Disable and Enable a field:

Set field as Read only.

Set field as editable(Enable).

Close window:

Close the current opened window.

Open New window:

Open a new browser window with specified URL."", 

Get Logged-in User ID:

Get the Logged-in User ID.
var userID = Xrm.Page.context.getUserId();

Attach Event to Control:

As CRM 2011 does not supports some events like onclick and ondblclick, we can attach a particular event to the control on form load.
function onload_method() {
    var control = document.getElementById("fieldName");
    if (control) {
        control.attachEvent("onclick", control_clicked);
        control.attachEvent("oncdbllick", control_dblclicked);

function control_clicked(){
    //This function fires on field click
    //onclick logic goes here

function control_dblclicked(){
   //This function fires on field double click
   //ondblclick logic goes here

Set Description field in E-mail entity:

The Description field in E-mail entity is inside an IFrame and since its made for text decoration, text inside this field is enclosed with html tags. So, we can't directly set the field value. Below is the solution to set this field OnLoad of the form.

function onload_method() {
    var descriptionFrame = document.getElementById('descriptionIFrame');
    descriptionFrame.attachEvent('onreadystatechange', setValue);

function setValue () {
    var descriptionFrame = document.getElementById('descriptionIFrame'); 
    if (descriptionFrame.readyState != 'complete')
    var htmlTag = "<:html> Value for Description field...<:/html>";
    var descriptionWindow = document.frames['descriptionIFrame'];
    descriptionWindow.document.body.innerHTML = htmlTag; 

Set IFrame URL:

To change the URL of IFrame and can also pass values in query string.

function setIFrameURL() {
    var IFrame = Xrm.Page.ui.controls.get("IFRAME_GoogleMap");
    var countryName ="address1_country").getValue();
    var newTarget= ""+countryName;

Get Schema Names of the Attributes:

To get the Schema Names of all the attributes in given entity.

function getSchemaNamesList(entityName) {
 var request = "<Request xsi:type='RetrieveEntityRequest'>" +
               "<MetadataId>00000000-0000-0000-0000-000000000000</MetadataId>" +
               "<EntityItems>IncludeAttributes</EntityItems>" +
               "<LogicalName>" + entityName + "</LogicalName>" +
               "<IsCustomizable>1</IsCustomizable>" +
               "<RetrieveAsIfPublished>true</RetrieveAsIfPublished>" +

 var result = queryMetadataService(request);
 var schemaNames = result.selectNodes("//EntityMetadata/Attributes/Attribute/SchemaName");
        var namesList = "";
        for (var i = 0; i < schemaNames.length; i++) {
  namesList += schemaNames[i].text +",";
        alert("Schema Names: "+namesList)

function queryMetadataService(request) {
 var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");"POST", '/mscrmservices/2007/MetadataService.asmx', false);
 xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
 xmlhttp.setRequestHeader("SOAPAction", '');

 var soapMessage = "<?xml version='1.0' encoding='utf-8'?>" +
 "<soap:Envelope xmlns:xsi='' " +
 "xmlns:xsd='' xmlns:soap=''>" +
 "<soap:Header>" +
 "<CrmAuthenticationToken xmlns=''>" +
 "<AuthenticationType xmlns=''>" + AUTHENTICATION_TYPE +
 "</AuthenticationType>" +
 "<OrganizationName xmlns=''>" + ORG_UNIQUE_NAME +
 "</OrganizationName>" +
 "<CallerId xmlns=''>00000000-0000-0000-0000-000000000000"+
 "</CallerId>" +
 "</CrmAuthenticationToken>" +
 "</soap:Header>" +
 "<soap:Body><Execute xmlns=''>" + request +
 "</Execute></soap:Body>" +

 return xmlhttp.responseXML;

Get Teams of User:

Get all the Teams User belongs to.

var xml = "" +
 "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
 "<soap:Envelope xmlns:soap=\"\" xmlns:xsi=\"\" xmlns:xsd=\"\">" +
 GenerateAuthenticationHeader() +
 " <soap:Body>" +
 " <RetrieveMultiple xmlns=\"\">" +
 " <query xmlns:q1=\"\" xsi:type=\"q1:QueryExpression\">" +
 " <q1:EntityName>team</q1:EntityName>" +
 " <q1:ColumnSet xsi:type=\"q1:ColumnSet\">" +
 " <q1:Attributes>" +
 " <q1:Attribute>name</q1:Attribute>" +
 " </q1:Attributes>" +
 " </q1:ColumnSet>" +
 " <q1:Distinct>false</q1:Distinct>" +
 " <q1:LinkEntities>" +
 " <q1:LinkEntity>" +
 " <q1:LinkFromAttributeName>teamid</q1:LinkFromAttributeName>" +
 " <q1:LinkFromEntityName>team</q1:LinkFromEntityName>" +
 " <q1:LinkToEntityName>teammembership</q1:LinkToEntityName>" +
 " <q1:LinkToAttributeName>teamid</q1:LinkToAttributeName>" +
 " <q1:JoinOperator>Inner</q1:JoinOperator>" +
 " <q1:LinkCriteria>" +
 " <q1:FilterOperator>And</q1:FilterOperator>" +
 " <q1:Conditions>" +
 " <q1:Condition>" +
 " <q1:AttributeName>systemuserid</q1:AttributeName>" +
 " <q1:Operator>EqualUserId</q1:Operator>" +
 " </q1:Condition>" +
 " </q1:Conditions>" +
 " </q1:LinkCriteria>" +
 " </q1:LinkEntity>" +
 " </q1:LinkEntities>" +
 " </query>" +
 " </RetrieveMultiple>" +
 " </soap:Body>" +

var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
xmlHttpRequest.setRequestHeader("SOAPAction", "");
xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
var resultXml = xmlHttpRequest.responseXML;

// Save all entity nodes in an array.
var entityNodes = resultXml.selectNodes("//RetrieveMultipleResult/BusinessEntities/BusinessEntity");

var teamnames = new Array();
var teamids = new Array();

for (var i = 0; i < entityNodes.length; i++) {

 var entityNode = entityNodes[i];
 var teamidNode = entityNode.selectSingleNode("q1:teamid");
 var teamNode = entityNode.selectSingleNode("q1:name");
 var teamid = (teamidNode == null) ? null : teamidNode.text;
 var team = (teamNode == null) ? null : teamNode.text;

 teamnames[i] = team;
 teamids[i] = teamid;

Filtered Lookup:

Filter the lookup view based the value selected in another lookup.

You can get fetchXml value from your CRM system by following the steps below.
Open Dynamics CRM
à Click Advanced Find on ribbon à Select Target(say) in "Look for:" list à Select Owning Team(Team) in list below à Select Team under Owning Team(Team) à Leave Equals as default filter à In Enter Value lookup select one record à Click Download Fetch XML on ribbon. You will get fetch XML string and put that code in variable 'fetchXml' in below code and replace GUID from 'value' property in <condition> tag with dynamic variable, here it is _teamId.

function changeCustomView() {
//new_targetvalue is a lookup to new_target entity which we are filtering present on new_test entity form
//new_team is a lookup to Team on new_test entity form by which new_targetvalue lookup filtering
//new_targetid is a primary key attribute in new_target entity
//teamid is a lookup to Team on new_target entity form
   var entityName = "new_target"; //Filtering lookup entity name
   var _team ="new_team"); //Team on which filtering depends on
   var viewDisplayName = "CustomTargetFilteredView";

   // If new_team contains a value, then filter the new_targetvalue lookup based on new_team selected
   if (_team.getValue() != null) {
      var _teamId = _team.getValue()[0].id;
      var viewId = "{1DFB2B35-B07C-44D1-868D-258DEEAB88E2}"; // Unique viewID
      var fetchXml = "<?xml version='1.0'?>" +
        "<fetch distinct='false' mapping='logical' output-format='xml-platform' version='1.0'>" +
        "<entity name='new_target'> <attribute name='new_targetid'/>" +
        "<attribute name='new_name'/>" +
        "<attribute name='createdon'/>" +
        "<order descending='false' attribute='new_name'/>" +
        "<link-entity name='team' alias='aa' to='owningteam' from='teamid'>" +
        "<filter type='and'>"+ 
        "<condition attribute='teamid' value='" + _teamId + "' uitype='team' operator='eq'/>" +
        "</filter> " +
        "</link-entity> " +
        "</entity> " +

      var layoutXml = "<grid name='resultset' " +
        "object='1' " +
        "jump='new_name' " +
        "select='1' " +
        "icon='1' " +
        "preview='1'>" +
        "<row name='result' " +
        "id='new_targetid'>" +
        "<cell name='new_name'/>" +
        "width='100' />" +
        "</row>" +

      var lookup = Xrm.Page.ui.controls.get("new_targetvalue");
      lookup.addCustomView(viewId, entityName, viewDisplayName, fetchXml, layoutXml, true);
      document.getElementById("new_targetvalue").setAttribute("disableViewPicker", "1");   

Trigger the Workflow:

Trigger the workflow(process) using javascript.

Steps to be followed to implement javascript to trigger workflow:
à Download JQuery here.
à Crate one JScript webresource and upload this downloaded JQuery.
à Create one JScript webresource for the below code and register to the CRM form where you want to run this script.

function TriggerWorkflow() {

 // Get the Workflow ID
 var workflowId = GetProcessId();
 if (workflowId[0].results.length > 0) {
  var xml = "" +
  "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
  "<soap:Envelope xmlns:soap=\"\" xmlns:xsi=\"\" xmlns:xsd=\"\">" +
  GenerateAuthenticationHeader() +
  "<soap:Body>" +
  "<Execute xmlns=\"\">" +
  "<Request xsi:type=\"ExecuteWorkflowRequest\">" +
  "<EntityId>" + + "</EntityId>" +
  "<WorkflowId>" + workflowId[0].results[0].WorkflowId + "</WorkflowId>" +
  "</Request>" +
  "</Execute>" +
  "  </soap:Body>" +
  "</soap:Envelope>" +
  var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
  xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", true);
  xmlHttpRequest.setRequestHeader("SOAPAction", "");
  xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
  xmlHttpRequest.setRequestHeader("Content-Length", xml.length);

function GetProcessId() {
 // Pass the workflow name manually to get the Id of the workflow
 var processName = "My Workflow Name";

 // Get the server URL
 var serverUrl = Xrm.Page.context.getServerUrl();
 var oDataUri = serverUrl + "/xrmservices/2011/OrganizationData.svc/WorkflowSet?$select=WorkflowId&$filter=Name eq '" + processName + "' and ActiveWorkflowId/Id ne null";
 var jSonArray = new Array();

  type: "GET",
  contentType: "application/json; charset=utf-8",
  datatype: "json",
  url: oDataUri,
  async: false,
  beforeSend: function (XMLHttpRequest) {
   XMLHttpRequest.setRequestHeader("Accept", "application/json");
  success: function (data, textStatus, XmlHttpRequest) {
   if (data && data.d != null) {
  error: function (XmlHttpRequest, textStatus, errorThrown) {
   alert("Error :  has occured during retrieval of the workflowId");
 return jSonArray;

Set field value using query string parameter:

When we click on some ribbon button or on some event, the new Account window will open with setting the Account Name field by passing that value in query string parameter.

function openAccountWindow(value) {
 var windowProperties = 'width=900,height=800,toolbar=no,directories=no,status=yes,menubar=no,scrollbars=yes,resizable=yes,modal=yes';
 var encodedParam = encodeURIComponent("name = New Test Account");"http://serverName/OrgName/main.aspx?etc=1&extraqs="+ encodedParam +"&pagetype=entityrecord",

Change the Status and Status Reason of the record:

We can not change the Status and Status Reason of the record directly or by REST call. We can do so using SOAP request. And Status and Status Reason should be matched to perform this action.
function SetState(entityName, entityId, statusReason, state) {
   var serverURL = Xrm.Page.context.getServerUrl();
   var setStateRequest = '<s:Envelope xmlns:s="">' +
    '<s:Body>' +
       '<Execute xmlns="" xmlns:i="">' +
          '<request i:type="a:UpdateRequest" xmlns:a="">' +
             '<a:Parameters xmlns:b="">' +
                '<a:KeyValuePairOfstringanyType>' +
                   '<b:key>EntityMoniker</b:key>' +
                   '<b:value i:type="a:EntityReference">' +
                      '<a:Id>' + entityId + '</a:Id>' +
                      '<a:LogicalName>' + entityName + '</a:LogicalName>' +
                      '<a:Name i:nil="true"></a:Name>' +
                   '</b:value>' +
                '</a:KeyValuePairOfstringanyType>' +
                '<a:KeyValuePairOfstringanyType>' +
                   '<b:key>State</b:key>' +
                   '<b:value i:type="a:OptionSetValue">' +
                      '<a:Value>' + state + '</a:Value>' +
                   '</b:value>' +
                '</a:KeyValuePairOfstringanyType>' +
                '<a:KeyValuePairOfstringanyType>' +
                   '<b:key>Status</b:key>' +
                   '<b:value i:type="a:OptionSetValue">' +
                      '<a:Value>' + statusReason + '</a:Value>' +
                   '</b:value>' +
                '</a:KeyValuePairOfstringanyType>' +
             '</a:Parameters>' +
          '<a:RequestId i:nil="true"></a:RequestId>' +
          '<a:RequestName>SetState</a:RequestName>' +
          '</request>' +
       '</Execute>' +
    '</s:Body>' +

   var req = new XMLHttpRequest();"POST", getServerUrlForSetState(), false);
   req.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
   req.setRequestHeader("SOAPAction", "");
   if (req.status != 200) {

Get the current form name:

Returns the name of the selected form in the record.

Refresh the form:

Refresh the current form.

Hide left navigation item:

Hide the left navigation item based on some condition.
var items = Xrm.Page.ui.navigation.items.get();

for (var i in items) {
   var item = items[i];

  if (item.getLabel() == "Accounts") {

Set field requirement level in run time:

Set the field requirement level to either Required or Recommended or NoConstraint in run time.
// No Constraint 

// Business Required 

// Business Recommended 

Get the CRM Organization URL:

Retrieve the CRM Organization URL with respect to the current domain name.
For example, if you are browsing the CRM instance with IP, then the return value would be like this: http(s)://<IP>/<OrgName>
If you are browsing with domain name, it would be like this: http(s)://<DomainName>/<OrgName>

function GetServerUrlRegExp(location) {
    var urlReg = new RegExp(/http[s]?:\/\/[0-9.:]+\/[^\/]+/);
    var ServerUrl = Xrm.Page.context.getServerUrl();
    if (window.location.href.match(urlReg) != null) {
        ServerUrl = window.location.href.match(urlReg).toString();
    if (ServerUrl.match(/\/$/)) {
        ServerUrl = ServerUrl.substring(0, ServerUrl.length - 1);
    return ServerUrl;

Subscribe to our YouTube channel :