Apr 9, 2011

SharePoint: get/set lookup using JavaScript

Hi guys,
Sometimes we need to get/set values of lookup fields at the client using JavaScript. The main problem is that the SharePoint renders as "select" and as complex of "input", "img", "select" (then we have more than 20 items in lookup field). I have the reciept:


function setLookUpValue(fieldCaption, lookupId, lookupValue){
var selectField = $('select[title="'+fieldCaption+'"]');
if (selectField.length) {
selectField.val(lookupId);
}
else{
var inputField = $('input[title="'+fieldCaption+'"]');
inputField.val(lookupValue);
var hidden = inputField.attr('optHid');
if (hidden != null)
$('input[id='+ hidden +']').val(lookupId);
}
}

function getLookUpValue(fieldCaption){
var selectField = $('select[title="'+fieldCaption+'"]');
if (selectField.length) {
return {'lookupId': selectField.val(), 'lookupValue': $('select[title="'+fieldCaption+'" option:selected]').text()};
}
else{
var inputField = $('input[title="'+fieldCaption+'"]');
var hidden = inputField.attr('optHid');
var hiddenValue = null;
if (hidden != null)
hiddenValue = $('input[id='+ hidden +']').val();
return {'lookupId': hiddenValue, 'lookupValue': inputField.val()};
}
}

PS. Don't forget to reference to jQuery