Skip to content

Instantly share code, notes, and snippets.

@havana59er
Created March 28, 2012 18:11
Show Gist options
  • Select an option

  • Save havana59er/2228909 to your computer and use it in GitHub Desktop.

Select an option

Save havana59er/2228909 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>
@Xogle

Xogle commented Jul 17, 2017

Copy link
Copy Markdown

For those looking at this wondering why it may not be working... the first line of code is no good.
var myAnnouncementText = document.getElementById('myAnnouncement').value();

Last line of code
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed); should be ctx not clientContext.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment