Sunday, October 7, 2012

Updating a list item in SharePoint list using ECMA Script

In this post I will explain how to update list item in SharePoint list using ECMA script. To update list items, firstly use getItemById (ID) function to fetch item to be updated and then set value for that item. 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(UpdateListItems, "sp.js");

function UpdateListItems()
{
  var clientContext = new SP.ClientContext.get_current();
  var oList = clientContext.get_web().get_lists().getByTitle('Employees');
 
  this.oListItem = oList.getItemById(2);
       
    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 Updated successfully');
  
 }

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

</script>

No comments:

Post a Comment