How to Get\Set Lookup Field using ECMAScript SharePoint 2010

In this post of LearningSharePoint.com we will explain how to get and set a lookup field using Ecmascript use -

Firstly, to get or retrieve a lookup field value see the below example -

function GetLookupValue()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(‘Testlist’);

var query = SP.CamlQuery.createAllItemsQuery();
allItems = list.getItems(query);
context.load(allItems, ‘Include(Title,Department)’);

context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}

function success() {

var TextFiled = “”;
var ListEnumerator = this.allItems.getEnumerator();

while(ListEnumerator.moveNext())
{
var currentItem = ListEnumerator.get_current();
TextFiled += currentItem.get_item(‘Title’) + ‘-’ +currentItem.get_item(‘Department’).get_lookupValue() + ‘\n’;
}
alert(TextFiled);
}

function failed(sender, args) {
alert(“failed. Message:” + args.get_message());
}

In the above ECMAScript Department is the Lookup and currentItem.get_item(‘Department’).get_lookupValue() will get you the value of the Lookup item selected.

Next Lets look at how to set a Lookup Field. >>

Related Posts