Thursday, November 11, 2010

Cross Site collection dropdown Look Up using JQuery

Often times you might need to do a sub-site or a cross site collection look up and populate it as a dropdown control in your SharePoint application. This is possible using JQuery. Here is the code for the same:

<script type="text/javascript" src="/sites/SPFix/JQueryDemo/JQueryDocumentLibrary/jquery-1.4.2.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
var soapEnv =
"<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'>
<soapenv:Body>
<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>
<listName>Tasks</listName>
<viewFields>
<ViewFields>
<FieldRef Name='Title' />
</ViewFields>
</viewFields>
</GetListItems>
</soapenv:Body>
</soapenv:Envelope>";

$.ajax({
url: "/sites/SharePointFix/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
complete: processResult,
contentType: "text/xml; charset="utf-8""
});
});

function processResult(xData, status) {
$(xData.responseXML).find("z\:row").each(function() {
$('#crossSiteCollectionLookUp').
append($("<option></option>").
attr("value",$(this).attr("ows_Title")).
text($(this).attr("ows_Title")));
});
};
</script>
<body>
<select id="crossSiteCollectionLookUp">
</select>
</body>

1. Download and install the jQuery library from http://www.jquery.com/

2. Upload the jQuery library in any of your SharePoint document library and refer the path in the script source URL highlighted above. For best practices on integrating jQuery with SharePoint, refer: http://weblogs.asp.net/jan/archive/2008/11/20/sharepoint-2007-and-jquery-1.aspx

3. Drag and drop the Content editor webpart where you want to show your dynamic dropdown lookup column to be visible.

4. Copy and paste the  above code in the Content Editor webpart. Change the highlighted sections like List name, Column name, URL and Display column names as required in your scenario.

In the code snippet above, I am dynamically populating the Title column from my Tasks List in a Dropdown control.

Should work like a charm :)