Subscribe: SharePoint SharePoint SharePoint

Saturday, June 22, 2013

Adding new ListItem to SharePoint List using ECMAScript

Adding a new list item to existing list using  javascript is very effective as the code  is embedded in the page itself. Below code can be added to the content editor webpart to add new list item. The code executes at Client Side, so its performance effective too.

<script type="text/javascript" src="//sharejpoint.googlecode.com/files/jPointLoader.js"></script>
<script type="text/javascript">

function createListItem() {
var clientContext = new SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle("ContactsList");
var itemInfo = new SP.ListItemCreationInformation();
this.listItem = list.addItem(itemInfo);



//The properties specified here are with regard to SP2013.
listItem.set_item('Title', 'My New Item!');
listItem.set_item('EMail0', 'abc@gmail.com');
listItem.set_item('CellPhone', 'xxxxxxxxxx');
listItem.set_item('_Comments', 'Hello');

listItem.update();

clientContext.load(listItem);

clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {

alert('Item created: ' + listItem.get_id());
}

function onQueryFailed(sender, args) {

alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>
<input type="button" ID="btnCreate" value="Create" onclick="createListItem()" />

0 comments:

Post a Comment