Introduction
In our projects sometimes a client comes up with a requirement such as:
- I need a new item created on a button click
- I need the total number of hits if I click on a button.
- 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.
- <script language="ecmascript" type="text/ecmascript">
-
- var clientContext = null;
- var oWeb = null;
- var oListColl = null;
- var oList = null;
- var oListItem = null;
- 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.
- function createListItem() {
- clientContext = new SP.ClientContext.get_current();
- oWeb = clientContext.get_web();
- oListColl = oWeb.get_lists();
- oList = oListColl.getByTitle('TestList');
- listItemCreationInfo = new SP.ListItemCreationInformation();
- oListItem = oList.addItem(listItemCreationInfo);
- oListItem.set_item('Title', 'New Item');
- oListItem.update();
- clientContext.load(oListItem);
- clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
- }
-
- function onQuerySucceeded() {
-
- alert(oListItem.get_title() + ' item is created successfully.');
- }
-
- function onQueryFailed(sender, args) {
- alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
- }
The following line of code is for placing the button:
- </script>
- <input id="btnCreateListItem" onclick="createListItem()" type="button" value="Create List Item"/>
Keep learning, Cheers.