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

1 comment:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a .Net developer learn from Dot Net Online Training from India. or learn thru ASP.NET Essential Training Online . Nowadays Dot Net has tons of job opportunities on various vertical industry.
    JavaScript Online Training from India

    ReplyDelete