Thursday, August 15, 2013

Get Choice Field values from SharePoint List using Javascript Client Object model

JavaScript Client Object model makes an Asynchronous call to the Server through WCF service and sends a XML request and then this request will be processed at the Server Side and return the JSON response.

Scenario:
To Get all the values of a Choice Field from SharePoint List and bind to a drop down control without using Server Side controls and Object model.
Solution:
We can use JavaScript Client Object model to retrieve the choice values and bind to the dropdown.
First, we need to Register the SP.js file in our code, through which only the HTTP request will be created and sent to the server. Registering this JS file is important since in SharePoint 2010 all the JS files will not be downloaded to the Client for better performance and only the required files will be downloaded to the Client.
You may now ask How does SharePoint ensure that only the required files are downloaded to the client machine? The answer is the SharePoint 2010 Script on Demand (SOD) framework. SOD ensures that only the required files are downloaded to the client and provides options to load them in the background after the page has completed loading. SOD is a class defined in the init.js file and contains methods for loading scripts, registering script dependencies, executing methods within a loaded page, and event notification. You use SOD to load the OOB SharePoint js files and your own JavaScript files.

 
<script>
SP.SOD.RegisterSod("SP.js", "\_layouts\SP.js");
 
/* Below line will make sure to call your JavaScript method only after the SP.js file loaded at Client side*/
ExecuteOrDelayUntilScriptLoaded(GetChoiceValues,"sp.js");
 
</script>
 

Below is the script will get all the choice values and adds to dropdown. Add a Content Editor web part to page and copy the below content to the HTML of the Content Editor webpart.
(Check the inline comments for more description)

 
<script type="text/javascript">
 
SP.SOD.RegisterSod("SP.js", "\_layouts\SP.js");
 
ExecuteOrDelayUntilScriptLoaded(GetChoiceValues,"sp.js");
 
function GetChoiceValues()
{
// Get the Client Context of the Current Web
var context = new SP.ClientContext.get_current();
var web = context.get_web();
 
// Get the list, Change the List name appropirately
this.taskList = web.get_lists().getByTitle("SportsTeam");
 
// Get Filed Collection from the List
this.fields= this.taskList.get_fields();
 
// Get the respective choice field (choice field) from the list using the Internal name
var deptChoiceField = context.castTo(this.taskList.get_fields().getByInternalNameOrTitle("SportsCategory"),SP.FieldChoice);
 
/* To Use all the objects and their properties we need to Load and Call the Execute method which creates the XML resquest and results us with the response*/
context.load(this.taskList);
context.load(this.fields);
context.load(deptChoiceField);
 
/*Here we are calling the Execute method after loading all the required properties*/
/*Based on the execution result, Sucess or Failure methods will be executed */
context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod),Function.createDelegate(this,this.onFailureMethod));
 
}
function onFailureMethod(sender, args) {
// We can the exact error details using get_message method of args
 alert("Error Occured: "+ args.get_message());
}
 
function onSuccessMethod(sender, args)
{
var context = new SP.ClientContext.get_current();
// Converting the Field to SPFieldChoice from the execution results
var myChoicesfield = context.castTo(this.fields.getByInternalNameOrTitle("SportsCategory"),SP.FieldChoice);
 
//get_choices() method will return the array of choices provided in the field
var choices = myChoicesfield.get_choices();
var elem = document.getElementById("Choices");
if(elem != "" && elem != undefined)
{
 divHtml ="<table><tr><td><select id='sports'> <option value='SelectSport' name='Sport'>Select Sport</option>";
 l= choices.length;
 
// Now here we are just looping through the array of choices and framing the html dropdown control
 for(i=0;i<choices.length;i++)
 {
   divHtml+="<option value='"+choices[i]+"'>"+choices[i]+"</option>";
 }
 divHtml+="</select></td><td><input type='button' id='gobutton' class='gobuttonStyle' value='Go' onclick='javascript:setQS()'/></td></tr></table>";
 elem.innerHTML = divHtml;
}
}
 
</script>
 
<div style="padding-left:15px;"id="Choices"></div>
 
 
 

 
Related Posts Plugin for WordPress, Blogger...