1
votes

I'm trying to just Javascript to add a list item when in SharePoint 2013 using the following code;

function createListItem(var lookup_Value) {

var clientContext = new SP.ClientContext.get_current();

var oList = clientContext.get_web().get_lists().getByTitle('CrewNoticesAudit');

var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);

oListItem.set_item('Title', 'My New Item!');
oListItem.set_item('NoticeId', lookup_Value);  // THIS IS A LOOKUP VALUE
oListItem.set_item('User', 'administrator');
oListItem.set_item('TimeStamp', new Date());
oListItem.set_item('AuditType', 'Open');

oListItem.update();

clientContext.load(oListItem);

clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), 
Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
alert('Item created: ' + oListItem.get_id());
}

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

The problem is that I'm getting one error "The field you are trying to update maybe read only" when I'm trying to run this code, I need to get the ID from the lookup list instead of the lookup value, is there a way to get the ID from a list with just the lookup value?

1

1 Answers

0
votes

A solution could be to get all the values from the lookup table(in this case allItems) and compare them with the desired valuecomparisonItemName() and so get the id. If the lookup table is small this shouldn't take long.

 var lookupVar = new SP.FieldLookupValue();    
  for (var i = 0; i < allItems.length; i++) {
        if (allItems[i].get_item("ItemName") == comparisonItemName) {
            lookupVar.set_lookupId(allItems[i].get_id());
        }
    }

Use lookupVar when setting the value for the item.

P.S. In order to get the exact item, write a CAML to get the desired item and than get the Id.