O365, SharePoint 2010, 2013, 2016: Updating List item by using JSOM

Applies to :

  • SharePoint Online – O365
  • SharePoint 2010
  • SharePoint 2013
  • SharePoint 2016

Below is the source code to update list item by using JSOM,

var CurrPageUrl;
var PageName;
var webUrl; 
var listName = "PageHitCounts";
var itemId = 1;
var tempPN;
var success = "success";
var failure = "failure";
var siteUrl="My Site URL";
var pagename;
var item;

$(document).ready(function() 
{
CurrPageUrl=window.location.href;
pagename =  CurrPageUrl.substring(CurrPageUrl.lastIndexOf("/") + 1, CurrPageUrl.lastIndexOf("."));
PageName = pagename;
ExecuteOrDelayUntilScriptLoaded(PageHitOnpageLoad, "sp.js");
 });
 function PageHitOnpageLoad()
 {
var clientContext = new SP.ClientContext.get_current();
var selectedItems = SP.ListOperation.Selection.getSelectedItems(clientContext);
     var oList = clientContext.get_web().get_lists().getByTitle("PageHitCounts");
         
     var camlQuery = new SP.CamlQuery();
     camlQuery.set_viewXml('<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' + 
         '<Value Type=\'Number\'>1</Value></Geq></Where></Query></View>');
     this.collListItem = oList.getItems(camlQuery);
     clientContext.load(collListItem);
     clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed)); 
} 

function onQuerySucceeded(sender, args) 
{
var listItemInfo = '';
var listItemEnumerator = collListItem.getEnumerator();        
     while (listItemEnumerator.moveNext()) 
     {
         var oListItem = listItemEnumerator.get_current();
         listItemInfo += oListItem.get_item(PageName);
         var count = +listItemInfo + +1;
         oListItem.set_item(PageName, count);
         oListItem.update();
         clientContext.ExecuteQuery();
     }
}

function onQueryFailed(sender, args) 
{
  alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

Hope this help.

Advertisements

One thought on “O365, SharePoint 2010, 2013, 2016: Updating List item by using JSOM

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s