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.
- //Variable to hold the value once returned from SharePoint client.svc
- var distinctChoices = [],
- // Function to return all of the choices from the Choice column passed in
- getUniqueColumnValuesFromChoice = function (columnName) {
- var ctx = new SP.ClientContext.get_current();
- var web = ctx.get_web();
- var list = web.get_lists().getByTitle('Your List Here');
- var field = list.get_fields().getByInternalNameOrTitle(columnName);
- var choiceField = ctx.castTo(field, SP.FieldChoice);
- ctx.load(field);
- // Call executeQueryAsync and pass in success and failure anonymous functions
- ctx.executeQueryAsync(function () {
- // Return array of all of the choices in the choice field
- distinctChoices = choiceField.get_choices();
- // Since call is asynchronous, call function to interact with the choices
- onFieldLoaded();
- },
- // This will be called when executeQueryAsync fails
- function (sender, args) {
- console.log(args);
- });
- };
- function onFieldLoaded() {
- // Not called until choices are loaded into distonctChoices array
- };
Comments
Anonymous
October 02, 2012
How do you call this function? I tried getUniqueColumnValuesFromChoice() and I tried to insert this code in the pageload, but it doesn't work, I had to rewrite the function to call it how do you call it?Anonymous
October 04, 2012
getUniqueColumnValuesFromChoice('ColumnName') so if the column name was Colors, you would call it like this: getUniqueColumnValuesFromChoice('Colors') You should be able to use the internal name or the column title.Anonymous
June 23, 2013
How to use this script in the content editor webpart and bind the choice value in to the html drop down?Anonymous
June 09, 2014
The comment has been removedAnonymous
October 28, 2014
I want to dynamically add choices based on certain conditions, how do i flush the data before adding new ones using this code?Anonymous
August 10, 2015
Hi , Can we cast the field to SP.FieldLookup to retrieve values from a lookup field?Anonymous
September 02, 2015
The comment has been removed