Sunday, October 7, 2012

Adding a list item in SharePoint list using ECMA Script

In this post I will explain how to create/add list item in SharePoint list using ECMA script. To create list items, firstly create a ListItemCreationInformation object, set its properties and pass it as parameter to the addItem(parameter) function of the list object. Then set the properties on the list item and finally call update() function to update list.

Add the below code in content editor web part and see the result
<script type="text/ecmascript">

ExecuteOrDelayUntilScriptLoaded(AddListItems, "sp.js");

function AddListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
 
  var listItemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(listItemCreateInfo);
       
    oListItem.set_item('Title', 'Somnath');
    oListItem.set_item('LastName', 'Matere');
    oListItem.set_item('WorkingUnit', 'IT');
       
    oListItem.update();

    clientContext.load(oListItem);

  clientContext.executeQueryAsync(Function.createDelegate(this,this.OnSuccess), Function.createDelegate(this,                 this.OnFailure));
  }

function OnSuccess()
{
 alert('Item Added successfully');
  
 }

function OnFailure(sender, args)
{
 alert('Request failed. ' + args.get_message() + '\n' +
 args.get_stackTrace());
  }

</script>

1 comment: