CRM 2013 – Using Dynamic Javascript

Javascript is a slippery beast, Slave to no one and master to many.   It’s just a quick blog post today, not as quick as this article I found written by me

CRM 2011 – Javascript snippet – How to remove all existing values from an OptionSet


I’m more happy in the .net and C# world with it’s static variables.

What I mean by this is C# you have to declare the variable you are going to use e.g.

  • string
  • int
  • bool
  • custom type


but with Javascript a var can be anything, it’s like something out of X-men changing and morphing it’s way along.

Here is a good article about static and dynamic languages

Static vs. dynamic typing of programming languages


Why doesn’t Hosk like Dynamic Javascript

Good question, surely I should like dynamic things.

Some of the reasons I don’t like it are

  • Hard to read/understand other peoples code
  • Bugs can be compiled and then appear in runtime when the code is run
  • It encourages the cowboy coders to go to town
  • It’s strange and different


Get to the point

I’m not saying I don’t like Javascript it’s just sometimes I want to do things and I’m not sure HOW because the syntax can be a bit crazy.  Like all developers once we have a working example in our hands, we are off.  So recently I saw some interesting Javascript in a project I am working and I was intrigued to understand how it worked and use it again.

One cool feature about Javascript is the ability to pass in function names using variables, a bit like reflection(ish), but only once you know how because I tried searching for this on the internet and fell down a big dark hole.



On a form I have 4 OptionSets which we are dynamically setting the values to.

If I pass in the OptionSetField name I can dynamically get the control

var control = Xrm .Page .getControl (OptionSetFieldName);

I can then clear this control

control. clearOptions();

I can then add in the new values and build it up.  The beauty of dynamic code is I can use the same code for all the OptionSets because I can pass in the name of the control.

When adding a the new optionSet values in, I can use a dynamic variable to retrieve the field name from array, which contains values retrieved from a fetchXML query.  The childField is the name of the field in CRM.

      var option = {
                    value: retrievedOptionSet[i]. text == "" ? "null" : retrievedOptionSet[0].attributes [childField]. value,
                    text: retrievedOptionSet[0].attributes [childField]. formattedValue
                control. addOption(option);


It may be common knowledge to all you JavaScript wizards out there, but I hadn’t used or seen JavaScript using dynamic names.  It makes sense and it’s very useful so I thought I would share it with you