Updating Sharepoint 2010 list item collection using Javascript client object model.

Tags

, , , ,

In order to update a list item collection using javascript client object model you have to follow the next steps:

  1. Create a function that retrieves the List Item Collection:

var myListItemCollection;

var myListcontext;

 function getMyListItems()

{

 try

{

myListcontext = new SP.ClientContext.get_current();

var web = myListcontext.get_web();

var myList = web.get_lists().getByTitle(‘MyList’);

var camlQuery = new SP.CamlQuery();

camlQuery.set_viewXml(“<View><Query><Where> <Eq><FieldRef Name=’Current’/><Value Type=’Integer’>1</Value></Eq> </Where></Query></View>”);

 this.myListItemCollection = myList.getItems(camlQuery);

 myListcontext.load(myListItemCollection);

/*Because you’re not on the server side you’ll call the executeQueryAsync method that takes two delegates as parameters the first one will be executed when your request is successful and the second if failed.*/

 myListcontext.executeQueryAsync(updateItems, onFailureMethod);

}

catch(exc)

{    alert(exc.message);   }

}

2. Create a method that will update the returning list item collection (This is the first parameter in myListcontext.executeQueryAsync method.)

function updateItems(sender, args)

{

try

{

var listItemEnumerator = myListItemCollection.getEnumerator();

while (listItemEnumerator.moveNext())

{

var myListItem = listItemEnumerator.get_current();

myListItem.set_item(‘Current’, ‘No’);

myListItem.update();

}

myListcontext.executeQueryAsync(ItemsUpdated, failureMethod);

}

catch(exc)

{       alert(exc.message);      }

}

function ItemsUpdated(sender, args)

{

alert(‘Items updated successfully’);

}

function failureMethod(sender, args)

{

alert(‘request failed ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());

}

So simple, isn’t it ? 🙂 … Best of luck.

Advertisements