Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save pridemusvaire/098174e2baab91ebb684fe851891a851 to your computer and use it in GitHub Desktop.
Save pridemusvaire/098174e2baab91ebb684fe851891a851 to your computer and use it in GitHub Desktop.
Create a new list item in SharePoint 2010 using javascript
<div>
<label for="myAnnouncement">Announcement</label>
<input id="myAnnouncement" type="text" /><br />
<input type="button" value="Post Announcement" />
</div>
<script type="text/javascript" >
// Use this to delay execution until the file sp.js has loaded. Also a good way to keep your context free of globals.
ExecuteOrDelayUntilScriptLoaded(function() {
// get announcement text
var myAnnouncementText = document.getElementById('myAnnouncement').value();
// get the SP context and list
var ctx = SP.ClientContext.get_current();
var targetList = ctx.get_web().get_lists().getByTitle('Announcements');
// create new list item
var itemCreateInfo = new SP.ListItemCreationInformation();
var newListItem = targetList.addItem(itemCreateInfo);
// set info for new item
newListItem.set_item('Title', 'MyNewAnnouncement');
newListItem.set_item('Body', myAnnouncementText);
newListItem.update();
// register unit of work with context
ctx.load(newListItem);
// we need to pass our newListItem to the onSuccess function. We do this with closure. Another method would be to use $.proxy
var onQuerySucceeded = function() {
var item = newListItem;
alert('Announcement created!\n\nId: ' + item.get_id() + '\nTitle: ' + item.get_item('Title'));
};
var onQueryFailed = function(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
};
// execute unit of work
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}, "sp.js");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment