Getting all values from a Choice field in SharePoint 2010 using JavaScript

I recently ran into an issue where I needed to get possible values for a SharePoint 2010 choice column.  Thought I would share the code in case anyone else runs across this need.  This code uses the ECMAScript Client-Side Object Model. 

 

  1. //Variable to hold the value once returned from SharePoint client.svc
  2.     var distinctChoices = [],
  3.         // Function to return all of the choices from the Choice column passed in
  4.         getUniqueColumnValuesFromChoice = function (columnName) {
  5.             var ctx = new SP.ClientContext.get_current();
  6.             var web = ctx.get_web();
  7.             var list = web.get_lists().getByTitle('Your List Here');
  8.             var field = list.get_fields().getByInternalNameOrTitle(columnName);
  9.             var choiceField = ctx.castTo(field, SP.FieldChoice);
  10.  
  11.             ctx.load(field);
  12.             // Call executeQueryAsync and pass in success and failure anonymous functions
  13.             ctx.executeQueryAsync(function () {
  14.                 // Return array of all of the choices in the choice field
  15.                 distinctChoices = choiceField.get_choices();
  16.                 // Since call is asynchronous, call function to interact with the choices
  17.                 onFieldLoaded();
  18.             },
  19.             // This will be called when executeQueryAsync fails
  20.             function (sender, args) {
  21.                 console.log(args);
  22.             });
  23.         };
  24.  
  25.     function onFieldLoaded() {
  26.         // Not called until choices are loaded into distonctChoices array
  27.     };