Get / Set value of a CRM Option Set Value field using javascript

 

Hello everyone,

In this tutorial we will cover how to work with crm option set value (OptionSetValue) fields using javascript in Microsoft Dynamics CRM.

This article covers examples about:

  • How to get an Option by passing value?
  • How to get selected CRM Option Set Valueitem?
  • How to get selected value of an CRM Option Set Value?
  • How to get Text of an CRM Option Set Value?
  • How to set an CRM Option Set Value (by numeric value)?
  • How to set an CRM Option Set Value by Text?

 

 How to get an Option by passing value?

The code below returns an Option object with text and value properties. value argument represents the numeric value of the optinonsetvalue field for searching the Option:

var myOption = Xrm.Page.getAttribute("fieldname").getOption(value);

 

How to get selected CRM Option Set Value item?

The code below returns the Option object with text and value properties:

var selectedOption = Xrm.Page.getAttribute("fieldname").getSelectedOption();

 

How to get selected value of an CRM Option Set Value?

The code below gives us the numeric value of selected OptionSetValue field:

var optionsetValue = Xrm.Page.getAttribute("fieldname").getValue();

 

How to get Text of an CRM Option Set Value?

The code below gives us the text of selected OptionSetValue field:

var optionsetText = Xrm.Page.getAttribute("fieldname").getText();

 

How to set an CRM Option Set Value (by numeric value)?

The code below helps us to set the value of OptionSetValue by a numeric value passed to the setValue function:

Xrm.Page.getAttribute("fieldname").setValue(value);

 

How to set an CRM Option Set Value by Text?

Actually we can’t set the selected item by text but we can search all options until we find the one whose text (label) is the same as one the one you have then get its value like below:


function setOptionSetValueByText("fieldname", optionText) {
    var options = Xrm.Page.getAttribute("fieldname").getOptions();
    for (i = 0; i < options.length; i++) {
        if (options[i].text == optionText) {
            Xrm.Page.getAttribute("fieldname").setValue(options[i].value);
        }
    }
}

I hope you enjoyed this tutorial.

See you 🙂

Comments

  • With the getOption method, you say “value argument can be either numeric value or string value for searching the Option”. Does this mean that ‘value’ can be either the Option Set value or the Option Set text? Or do you mean the Option Set value can be formatted as either a number or a string?

    • Hi,

      Thanks to your comment I realized the mistyping and fixed it. value argument represents the numeric value of optionsetvalue field. So getOption() method accepts only numeric value as parameter.

      Kind Regards,

      Mehmet.

Leave a Reply

Your email address will not be published. Required fields are marked *