Javascript to set a text field in CRM 2011 to a certain value

Step 1 - create a web resource

Example a - simple example where you set a field to a hard coded value

function Updatefield()

{

var Currentvalue = Xrm.Page.getAttribute("description").getValue();

var Newvalue = " test";

Xrm.Page.getAttribute("description").setValue(Newvalue);

}

Example b - a more complex example where you set a value of a field based on the value of another field

In this example, there is a custom "two option field" on a form called "new_orderpad" - the user can select yes or no on the form. If the user selects a yes, we want the description field to be set to a certain value. If the user selects a no, we want the description field on the form to be set to a certain values. Note that two option fields are actually stored in the database as a true or a false so that is why the if statements check for true or value.

function Updatefield()

{

var Order = Xrm.Page.getAttribute("new_orderpad").getValue();

var Currentvalue = Xrm.Page.getAttribute("description").getValue();

if (Order == true)

{

var Newvalue = " test when yes";

Xrm.Page.getAttribute("description").setValue(Newvalue);

}

else if (Order == false)

{

var Newvalue = " test when no";

Xrm.Page.getAttribute("description").setValue(Newvalue);

}

else

{

var Newvalue = "Unknown";

Xrm.Page.getAttribute("description").setValue(Newvalue);

}

}

NOTE: you have to reference the field name properly. In CRM, when you pull up the fields for a given entity, the screen shows you 3 names: "Name", "Schema Name" and "Display Name". Use the one called "Name".

NOTE 2: the field names are case sensitive: in the above example, you have to use "description" NOT "Description". It is case sensitive.

Step 2 - Modify your form to point to this web resource

a) Add a reference to the web resource you created in step 1 by going to the field's "form libraries" settings and referencing the above code.

b) Then add an "event handler" to some field's on change event. In the "function" field, use "Updatefield".

NOTE: do not put use Updatefield() - use "Updatefield". Leave out the () part.