Create Lookup Site Column using JavaScript

Steps
  1. Create a Separate page in SharePoint site and a content editor Webpart.
  2. Upload the JavaScript code to site Assests and copy the link.
  3. Edit the CEWP and add the path of the script txt file and save it.
  4. Enter the list name and click the create list button and refresh the page.
  5. The list created in SharePoint site.

  1. $( document ).ready(function() {   
  2.         CreateSiteLookupColumn();     
  3.  });     
  4.       var clientContext;    
  5.       var oWebSite;    
  6.       var oList;    
  7.       function CreateSiteLookupColumn()    
  8.       {    
  9.          clientContext= new SP.ClientContext.get_current();     
  10.          oWebSite= clientContext.get_web();    
  11.          //Lookup List    
  12.          oList=oWebSite.get_lists().getByTitle('TestList');    
  13.          clientContext.load(oList);    
  14.          clientContext.load(oWebSite);    
  15.          clientContext.executeQueryAsync(function () {    
  16.                  var fieldXml="<Field Name='Country' DisplayName='Country' Type='Lookup' Required='FALSE' Group='Operations'/>";    
  17.                  var lookupField=oWebSite.get_fields().addFieldAsXml(fieldXml,true,SP.AddFieldOptions.addFieldCheckDisplayName);    
  18.   
  19.                 //Cast to Lookup field to set List Name and lookup column       
  20.     
  21.                  var fieldLookup = clientContext.castTo(lookupField, SP.FieldLookup);    
  22.                  fieldLookup.set_lookupList(oList.get_id());    
  23.                  fieldLookup.set_lookupField("Title");    
  24.                  fieldLookup.update();                
  25.                  clientContext.executeQueryAsync(function () {     
  26.                          alert('Look up Field Added successfully');     
  27.                       }, function (sender, args) {     
  28.                             alert(args.get_message() + '\n' + args.get_stackTrace());     
  29.                       });     
  30.          },function (sender, args) {     
  31.           alert(args.get_message() + '\n' + args.get_stackTrace());     
  32.       });       
  33.  } 
Save the page and check the list settings field added successfully.
Ebook Download
View all
Learn
View all