Cry about...
Dynamics CRM 2011 How To


How to get or set the text of an OptionSet field (JavaScript)


The value of a field that is an OptionSet is obtained the same way as with any other field, i.e.:

var value = Xrm.Page.getAttribute("optionSetField").getValue();

But this returns the value and not the text, so 1, 2, 13123212. To get the text and not the value use:

var value = Xrm.Page.getAttribute("optionSetField").getText();

If you want to set the value of the field then this is done the same way as thought it were a simple text field:

Xrm.Page.getAttribute("optionSetField").setValue(1);

but this is setting the value. If you know the text that you want selected but not the corresponding value then how do you do this? The best you can do is to search though the available options looking for one with the right text, so:

var newText = "apples";
var optionField = Xrm.Page.getAttribute("optionSetField");
var options = optionField.getOptions();
for (var i=options.length-1;i>=0;i--) {
  if (options[i].text == newText) {
    optionField.setValue(options[i].value);
  }
}

It might be more convenient to wrap this up in a function, something like:

Cryer.SetOptionText = function (attributeName, newText) {
  var optionField = Xrm.Page.getAttribute(attributeName);
  var options = optionField.getOptions();
  for (var i = options.length - 1; i >= 0; i--) {
    if (options[i].text == newText) {
      optionField.setValue(options[i].value);
      return;
    }
  }
  optionField.setValue(null);
}


These notes have been tested with Microsoft Dynamics CRM 2011, and may apply to other versions as well.



About the author: is a dedicated software developer and webmaster. For his day job he develops websites and desktop applications as well as providing IT services. He moonlights as a technical author and consultant.