Wednesday, September 13, 2017

Set and Unset Multi-Select Lookup field values in SharePoint Online

If you ever need an event to set the values of a multi-select lookup field in SharePoint, you can use the following:

function SetLookup() 
{
// define the items to add to the results (i.e already selected) this the visual part only   
var $resultOptions = "<option title='MyValue' value='2'>MyValue</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 = "2|tMyValue";   
 
// remove the option selected.  NOTE: These are in alphabetical order and thus this ID may differ from the select value   
//$("[id$='_SelectCandidate'] option:eq(1)").remove();  
$("[id$='_SelectCandidate'] option[value='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);   
}

function UnsetLookup() 
{
// define the items to add to the results (i.e already selected) this the visual part only   
var $resultOptions = "<option title='MyValue' value='2'>MyValue</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 = "2|tMyValue";   
 
// remove the option selected.  NOTE: These are in alphabetical order and thus this ID may differ from the select value   
$("[id$='_SelectResult'] option:eq(1)").remove();  
$("[id$='_SelectResult'] option[value='2']").remove();  

// append the new options to our results (this updates the display only of the second list box)   
$("[id$='_SelectCandidate']").append($resultOptions);  

// append the new options to our hidden field (this sets the values into the list item when saving)   
var value = $("[id$='MultiLookup']").val();
value = value.replace($resultSpOptions, "");

//alert('value: ' + value);
$("[id$='MultiLookup']").val($resultSpOptions);   
}


//Execute the Query.
$(document).ready(function(){

// In this case, we're triggering by a dropdown named DropdownToTrigger
$('select[title="DropdownToTrigger"]').on('change', function() {
if ($(this).val()=='Something') 
{
SetLookup();
   } 
   else
   {
UnsetLookup();
   }
});


});

No comments: