Add, Update and Delete list items using ECMAScript
Introduction
In this post we will see how to Add, Update and Delete SharePoint list items with ECMAScript (aka javascript client object model)- Add item to SharePoint list
- Update item of SharePoint list
- Delete item from SharePoint list
Add item to SharePoint list
To add an item to the list, use the ListItemCreationInformation object,set the properties using set_item, call the update and ExecuteQueryAsync methods
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| function AddListItem(){ var ListName = "MyList"; var context = new SP.ClientContext.get_current(); // the current context is taken by default here //you can also create a particular site context as follows //var context = new SP.ClientContext('/Sites/site1'); var lstObject = context.get_web().get_lists().getByTitle(ListName); var listItemCreationInfo = new SP.ListItemCreationInformation(); var newItem = lstObject.addItem(listItemCreationInfo); newItem.set_item('Title', 'This is new item'); // set values to other columns of the list here newItem.update(); context.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailure)); function onSuccess() { alert('Item created: ' + newItem.get_id()); } function onFailure(sender, args) { alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); }} |
Update Item of SharePoint list
function UpdateListItem(){var ListName = "MyList";var context = new SP.ClientContext.get_current(); // the current context is taken by default here//you can also create a particular site context as follows//var context = new SP.ClientContext('/Sites/site1');var lstObject = context.get_web().get_lists().getByTitle(ListName);this.lstObjectItem = lstObject.getItemById(1);lstObjectItem.set_item('Title', 'This is updated item');lstObjectItem.update();lstObject.set_description("Updated description using ECMAScript");lstObject.update();context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),Function.createDelegate(this, this.onFailure));}function onSuccess() {alert('Item udated');}function onFailure(sender, args) {alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());}Delete Item from SharePoint list
function DeleteListItem(){var ListName = "MyList";var context = new SP.ClientContext.get_current(); // the current context is taken by default here//you can also create a particular site context as follows//var context = new SP.ClientContext('/Sites/site1');var lstObject = context.get_web().get_lists().getByTitle(ListName);this.lstObjectItem = lstObject.getItemById(1);lstObjectItem.deleteObject();context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),Function.createDelegate(this, this.onFailure));}function onSuccess() {alert('Item Deleted');}function onFailure(sender, args) {alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());}
No comments:
Post a Comment