Add ListItem with Lookup Field using Client Object Model (ECMA)

Below is the javascript required to add an item to a list that contains a lookup field.

In my example, my C# code is generating links to javascript functions.

I have two lists: one list, TeamList holds teams and their members for our various school houses:

Team Name (‘Title’ column, renamed)
Team Members (PeoplePicker)
House (single line of text)

The other list, TeamDutyDates, stores each team’s assignment to a particular duty date:

Title (not used, hidden)
Team (lookup to Title column of TeamList)
Duty Date (Date field to hold the date of the duty)

The code is embedded in to my user control with a tag.

function addListItem(teamName, teamID, date) {
var ctx = new SP.ClientContext('/TheSiteWithMyList');
var oList = ctx.get_web().get_lists().getByTitle('TeamDutyDates');
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('DutyDate',new Date(date));

var lookupVar = new SP.FieldLookupValue();
ctx.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

function onQuerySucceeded() {
// here you can put any code that works with the newly created item.
// in this example, I work with the data in the list item to select a table cell by ID and change its css and content
var addedItemId = oListItem.get_id();
var teamName = oListItem.get_item('Team').get_lookupValue();
var teamID = oListItem.get_item('Team').get_lookupId();
var dutyDate = oListItem.get_item('DutyDate');

//The following code converts the date value into a simple yyyy/MM/dd date
var dutyDateObj = new Date(dutyDate);
var day = "" + dutyDateObj.getDate();
if (day.length == 1) {
day = "0" + day;
var month = "" + (dutyDateObj.getMonth() + 1);
if (month.length == 1) {
month = "0" + month;
dutyDate = dutyDateObj.getFullYear() + "/" + month + "/" + year;

//get the cell using jQuery - match on END of id due to ID generation
var cell = $("[id$='" + teamName + "_" + dutyDate + "']");
cell.html("<a href=.... some javascript to deselect this cell and delete list item...");

function onQueryFailed(sender, args) {
alert('Could not add new duty: ' + args.get_message() + '\n' + args.get_stackTrace();


One Trackback to “Add ListItem with Lookup Field using Client Object Model (ECMA)”

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: