Sharepoint help

Posted on 2013-06-26
Medium Priority
Last Modified: 2013-07-30

I am trying to use Javascript object model in SharePoint 2010 and here is my scenario. I have two lists with parent child relationship. Authors and books.

Now I want to retrive all the books that are published by a particular author. so assume we are in the context of the parent list Item (i,e a list Item in Authors) when writing the script to get all the books authored by a particular author.

So here is what I want to get the statistics using Javascript Client Object model:

-1) Count of All the books authored by a particular author

-2) Count of  All the books authored by a particular author but have a status = Not Started.

-3) 2 divided by 1  store in a variable so I can use this fraction for some display

-4)Count of  All the books authored by a particular author but have a status = In Progress.

-5) 4 divided by 1  store in a variable so I can use this fraction for some display

-6)Count of  All the books authored by a particular author but have a status = Complete.

-7) 6 divided by 1 and store in a variable so I can use this fraction for some display

Can anyone please help with the script please? I am new to Javascript and Javascript client object model in Sharepoint

Thanks in Advance,
Question by:Techsavy
1 Comment
LVL 44

Accepted Solution

Rainer Jeschor earned 2000 total points
ID: 39303106
a good starting point is:

Even if he does not post all his used scripts, the main idea beyond ECMAScript is understandable (please follow also part 4 of this series).

Here is some sample code I built on my dev environment where the books list is named "EEBooks" and has a lookup field in it named "Author". As the components used by ECMAScript needs the internal field names, the internal name of the Author field is "Author0" (thats a ZERO) as the SharePoint built-in field "Created by" has the internal name "Author".

<!-- HTML area for author search input box, action button and result output -->
<tr><td>Author Name:</td><td><input type="text" name="authname" id="authname" /></td></tr>
<tr><td colspan="2"><input type="button" text="Search..." onclick="javascript:GetBooksByAuthor();" value="Search ..." /></td></tr>
<div id="results"></div>
<script type="text/javascript" src="//ibms.gbi.msg.de/test/SiteAssets/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
<!-- Get book counts by author --> 
var bookItems;
var booksCount;
var booksCountNotStarted;
var booksCountInProgress;
var booksCountComplete;
var booksCountOther;
var booksPercentageComplete;
var booksPercentageNotStarted;
var booksPercentageInProgress;

// This is the main function.
function GetBooksByAuthor() 

  // Get the author from input box
  var selectedAuthor = jQuery("#authname").val();
  if (selectedAuthor == "") 
	// Do nothing if nothing entered
	alert('Please enter a value');

  // Create query string using CAML syntax 
  var myQueryString = '<View><Query><Where><Eq>' +
                  '<FieldRef Name=\'Author0\' />' +
                  '<Value Type=\'Lookup\'>'+ selectedAuthor +'</Value></Eq></Where>' +
  // Create client context 
  var myContext = new SP.ClientContext.get_current(); 
  // Get current web (comparable to SPWeb) 
  var myWeb = myContext.get_web(); 
  // Get list by title (comparable to SPList) 
  var myList = myWeb.get_lists().getByTitle('EEBooks'); 
  // Create (empty) query (comparable to SPQuery) 
  var myQuery = new SP.CamlQuery(); 
  // Attach query string to query 
  // Get items from list using query 
  bookItems = myList.getItems(myQuery); 

  // Declare what to load (bookItems with the fields ID, Title, Status
  // Now execute the query. 
                                this, GetBooksByAuthorSuccess),
                                this, GetBooksByAuthorFail)); 
  jQuery("#results").html("Query is executed asynch ...");

// This function will be called if the
// "executeQueryAsync" failed
// (e.g. list not available, query string wrong or anything else) 
function GetBooksByAuthorFail(sender, args) 
  // Show error message
  alert('GetBooksByAuthor() failed:' + args.get_message()); 

// This function will be called if the "executeQueryAsync"
// succeeded 
function GetBooksByAuthorSuccess(sender, args) 
  // Initialize counters
  booksCountNotStarted = 0;
  booksCountInProgress = 0;
  booksCountComplete = 0;
  booksCountOther = 0;
  booksPercentageComplete = 0;
  booksPercentageNotStarted = 0;
  booksPercentageInProgress = 0;
  // Now we can use the data retrieved from SharePoint! 
  // Get number of items 
  var booksCount = bookItems.get_count(); 

  // Get the enumerator to be able to loop through the items
  var booksEnumerator = bookItems.getEnumerator(); 
  // Declare temporary variable for output 
  var outputDetails = '';

  // Loop through all items 
  while (booksEnumerator.moveNext()) 
    // Get current item 
    var currentBook = booksEnumerator.get_current(); 
    // Update Counter based on status 
    switch (currentBook.get_item("Status")) {
      case "Complete":
        booksCountComplete += 1;
      case "In progress":
        booksCountInProgress += 1;
      case "Not started":
        booksCountNotStarted += 1;
        booksCountOther += 1;

  // Build percentages and update result div
  if ( booksCount > 0 )
    booksPercentageComplete = booksCountComplete / booksCount;
    booksPercentageNotStarted = booksCountNotStarted / booksCount;
    booksPercentageInProgress = booksCountInProgress / booksCount;    
  outputDetails = 'Results:<br/><br/>Total books: ' + booksCount + '<br/>' 
                + 'Books not started:' + booksCountNotStarted +' / Percentage ' + booksPercentageNotStarted +'<br/>'
                + 'Books in progress:' + booksCountInProgress +' / Percentage ' + booksPercentageInProgress +'<br/>'
                + 'Books completed:' + booksCountComplete +' / Percentage ' + booksPercentageComplete +'<br/>';  

Open in new window

Some comments from my experience:
ECMAScript is sometimes really complex compared to e.g. using the SPServices library (available on Codeplex). Also debugging is really hard ...
An additional tip would be to create a dynamic drop-down list (SELECT element in HTML) to choose an author from and add the options also via COM (Client Object Model) with one additional (first) entry: "Please select an author ...".

Instead of editing the SharePoint page in SharePoint designer, I normally use one text file containing all the HTML and script stuff, upload this to a document library and use then a Content Editor Web Part to link to this file. Then changes can simply be done by uploading a new version of this text file.


Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
One day, as you try to send an email from your SharePoint account, an error message appears saying: “E-mail Message Cannot be Sent.” You may have outgoing email settings misconfigured.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

589 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question