Monday, August 14, 2017

SharePoint Online: Set the default value for a Lookup (SPFieldLookupMulti) column

The following code will set the value for a Lookup field in SharePoint, where the highlighted fields are what you'd need to update.

           // define the items to add to the results (i.e already selected) this the visual part only  
           var $resultOptions = "<option title='Veeva Vault' value='3'>Veeva Vault</option>";  
           // this is the list of initial items (matching the ones above) that are used when the item is saved.  '|t' is the divider
           var $resultSpOptions = "3|Veeva Vault";  
            
           // remove the option selected on the left side.  NOTE: These are in alphabetical order and thus this ID will probably differ from the select ID (and is 0 based)
           $("[id$='_SelectCandidate'] option:eq(2)").remove(); 

           // append the new options to our results (this updates the display only of the second list box)  
      $("[id$='_SelectResult']").append($resultOptions); 
            // append the new options to our hidden field (this sets the values into the list item when saving)  
      $("[id$='MultiLookup']").val($resultSpOptions);   

You can get the values by using the developer tools (e.g. pressing F12 in Chrome) and inspecting the picker element:



you'll see:


where targeting 3 would result in the code above.

Shout out to this blog post which helped, just needed some minor tweaks to work in SharePoint Online.

No comments: