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. var clientContext = null;
  3. var oWeb = null;
  4. var oListColl = null;
  5. var oList = null;
  6. var oListItem = null;
  7. 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(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
  12. }
  13. function onQuerySucceeded() {
  14. alert(oListItem.get_title() + ' item is created successfully.');
  15. }
  16. function onQueryFailed(sender, args) {
  17. alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
  18. }
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.