CAML Query to Filter Lookup Field by Id using JSOM in Office 365 / SharePoint 2013

Introduction

Few days ago, I wrote a post about how to Create a new lookup field using JSOM in Office 365. Continuing with the same scenario, we have two related libraries: Documents and Pages, and the requirement is to see for every page one list of related documents.

So, the first step, was creating a lookup value in order to allow us to relate two libraries. And the next step, which is the post topic, is to use JSOM (JavaScript) code in a script webpart to query Documents library filtering by current page id, that means filtering by using Lookup ID column.

image

If you look at the picture, this is how lookup field is filled in the Documents library.

And here is the code we need to use using a Script WebPart or Content Editor WebPart inside the Pages Library documents or pages.

Note: This is important to note that this code is using some context variables related to current page id and this code is only working if that is inside a page. For example, if we have a page like that:

image

Note: We can try / debug our code using F12 (Developer Tools in Chrome or IE).

Code

Here is the code to achieve the image results:

 

Author: José Quinto
Link: https://blog.josequinto.com/2015/12/17/caml-query-to-filter-lookup-field-by-id-using-jsom-in-office-365-sharepoint-2013/
Copyright Notice: All articles in this blog are licensed under CC BY-SA 4.0 unless stating additionally.