Introduction
This article explains how to delete an item in a list in SharePoint 2013 using CSOM-JavaScript.
Prerequisites
- Ensure you have access to the Office 365 online.
- Ensure Napa tool is available in your site.
Steps to be followed
- Create an app for SharePoint using Office 365 Tools. If you have missed out on how to create an app in SharePoint 2013, then, Click here.
- Create a list and name it “MyCustomList”. Click here if you want to learn how to create a list.
- Click on Default.aspx page.
- Add an input text box to capture the id details and a button to delete an item, by id provided in the TextBox..Place the following code inside the “PlaceHolderMain” tag.
Enter the Item ID: <input typr="text" name="txtID" id="txtID"></input><br/><br/><br/>
<button id="btnDeleteItem" onclick="deleteItem()">Delete Item</button><br/>
- Click on the "App.js" file.
- Globally declare the content, web and list objects as shown below.
var context = SP.ClientContext.get_current(); //gets the current context
var web = context.get_web(); //gets the web object
var list = web.get_lists(); //gets the collection of lists
var targetList;
- Now write the function to delete an item in a list as in the following:
function deleteItem() {
targetList = list.getByTitle("MyCustomList");
context.load(targetList);
var itemId = document.getElementById("txtID").value;
alert(itemId);
var itemToDelete = targetList.getItemById(itemId);
itemToDelete.deleteObject();
targetList.update();
context.executeQueryAsync(deleteItemSuccess, deleteItemFailed);
}
- In the preceding sample code snippet we are deleting an item in a list based on the item id that is captured through the text box.
- “deleteObject” is the method to delete an item from the list using the listitem object.
- Now execute the code by calling executeQueryAsync().
function deleteItemSuccess() {
var listItemInfo = 'Item deleted: ';
alert(listItemInfo);
}
function deleteItemFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
- That’s it!! Now let's start testing.
Testing
- Now to run the app click on the "Play" button that is available towards the left-most corner.
- The app is packaged, deployed and installed on your Office 365 Site.
- Now you will be able to see the following page.
- Before entering the id let's open it in a new tab to navigate to the “MyCustomList” list.
- Just go to the following URL:
Syntax: https://yoursite/Lists/ListName
Example: https://mysite/Lists/MyCustomList
- In “MyCustomList” we are able to see 5 items.
- Let’s proceed to delete the item with the id 5.
- Enter the number 5 in the text bax as shown below and click on the “Delete Item” button.
- To see the item that was deleted, return to the “MyCustomList” URL.
- Now uou can see that the item id 5 is not available in the list.
- Thus the item was deleted from the list.
Summary
Thus in this article you saw how to delete an item in a list in SharePoint 2013 using CSOM-JavaScript.