Introduction
One person commented that - he needs to know How to Add, Update and Delete SPListItem in a SPList using JavaScript Object Model in a previous blog post. So I thought of writing a post for him; and which may useful for other new SharePoint newbies too.
Solution
Add
- function Add() {
- var clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
- var oList = oWeb.get_lists().getByTitle('List1');//Get SPList by Title
- var itemCreateInfo = new SP.ListItemCreationInformation();
- var oListItem = oList.addItem(itemCreateInfo);
- oListItem.set_item('Title', 'Value'); //Title is the field and Value is the value for field
- oListItem.update();
- clientContext.load(oListItem);
- clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
- //Function when the execution of the query successed
- function onQuerySucceeded(sender, args) {
- alert('Data ADDED successfully');
- };
- //Function to run when the execution falis
- function onQueryFailed(sender, args) {
- alert('Cannot ADD');
- };
- };
Update
- function Update() {
- var clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
- var oList = oWeb.get_lists().getByTitle('List1');//Get SPList by Title
- var oListItem = oList.getItemById(1);//Get the list item by id
- oListItem.set_item('Title', 'New Value');
- oListItem.update();
- clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
- //Function when the execution of the query successed
- function onQuerySucceeded(sender, args) {
- alert('Data UPDATED successfully');
- };
- //Function to run when the execution falis
- function onQueryFailed(sender, args) {
- alert('Cannot UPDATE');
- };
- };
Delete
- function Delete() {
- var clientContext = new SP.ClientContext();
- var oWeb = clientContext.get_web();
- var oList = oWeb.get_lists().getByTitle('List1');//Get SPList by Title
- var oListItem = oList.getItemById(1);//Get the list item by id
- oListItem.deleteObject();
- clientContext.executeQueryAsync(Function.createDelegate(this, onQuerySucceeded), Function.createDelegate(this, onQueryFailed));
- //Function when the execution of the query successed
- function onQuerySucceeded(sender, args) {
- alert('Data DELETED successfully');
- };
- //Function to run when the execution falis
- function onQueryFailed(sender, args) {
- alert('Cannot DELETE');
- };
- };
You can download the entire solution from the below url. https://drive.google.com/file/d/0ByEnOE8DAdvhSWFfM0Jja1FHMms/edit?usp=sharing
No comments:
Post a Comment