Click Event to Create a New Item Using ECMAScript

Introduction

 
In our projects sometimes a client comes up with a requirement such as: 
  1. I need a new item created on a button click
  2. I need the total number of hits if I click on a button.
  3. Many more requirements on a button click
So what normally we will do is use Visual Studio to create a page with an asp button and write our code to work as per our requirements, thereby requiring a lot of time to develop.
 
Here I will show you a very easy process to use a button click event using JavaScript.
 
Take a page, or take a form. Add a content editor to the page and paste in the following code.
  1. <script language="ecmascript" type="text/ecmascript">    
  2.     
  3. var clientContext = null;    
  4. var oWeb = null;    
  5. var oListColl = null;    
  6. var oList = null;    
  7. var oListItem = null;    
  8. var listItemCreationInfo = null;   
The following code is for creating a new item, you can use it for any update on the click event by modifying the code below.
  1. function createListItem() {    
  2. clientContext = new SP.ClientContext.get_current();    
  3. oWeb = clientContext.get_web();    
  4. oListColl = oWeb.get_lists();    
  5. oList = oListColl.getByTitle('TestList');    
  6. listItemCreationInfo = new SP.ListItemCreationInformation();    
  7. oListItem = oList.addItem(listItemCreationInfo);    
  8. oListItem.set_item('Title''New Item');    
  9. oListItem.update();    
  10. clientContext.load(oListItem);    
  11. clientContext.executeQueryAsync(Function.createDelegate(thisthis.onQuerySucceeded), Function.createDelegate(thisthis.onQueryFailed));    
  12. }    
  13.     
  14. function onQuerySucceeded() {    
  15.     
  16. alert(oListItem.get_title() + ' item is created successfully.');    
  17. }    
  18.     
  19. function onQueryFailed(sender, args) {    
  20. alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());    
  21. }   
The following line of code is for placing the button:
  1. </script>    
  2. <input id="btnCreateListItem" onclick="createListItem()" type="button" value="Create List Item"/>   
Keep learning, Cheers.


Similar Articles