Thursday, June 17, 2010

Setting 20+ Lookup value at client side, JQuery

I have faced the issue many time when setting the value into sharepoint controls at client side. Here i will explain how to set the value in 20+ lookup control at client side using JQuery. First I tried to setting a value into its textbox and then firing a change event of textbox but that doesn't work. If you use JQuery to raise change event like this


This event carry the srcElement property null that results in crash of "HandleChange" function in the start.

And if you try to raise the event like this


There are many prerequisites to this approach like you have to first raise the click of lookup that will render the options in the DOM internally and then you have to select the appropriate option like this

var LookupInput = $("[Title='TitleOfControl']");;
$("select[id='" + LookupInput.attr("opt") + "']").find("option[value='"+ SelectedValue +"']").attr("selected","true");

and then raise the change event. This approach will only work if there are no duplicate text in the lookup otherwise it will fail.

Finally then i come to the following straight forward and working solution

var LookupInput = $("[Title='TitleOfControl']");
$("input[id='" + LookupInput.attr("opthid") + "']").val("SelectedValue");

In this solution you need to set the value in TextBox, "opt" attribute of TextBox and in Hidden field "opthid" that is mentioned in attribute of TextBox. This solution worked for me like charm. Hope it will help others too.

HandleChange function that is called when lookup's textbox value changes
function HandleChange()
var ctrl=event.srcElement;
var str=ctrl.value;
var opt=document.getElementById(ctrl.opt);
ctrl.match=FilterChoice(opt, ctrl, str, "");

No comments:

Post a Comment