6

I have a Multi select Look up column which as you all know is a control with two list boxes and "Add or Remove" Buttons.

The user populates the right-hand side of the control with some values by clicking the Add button; I have saved those selected values into array. Now the user changes an option in a cascading dropdown which actually populates this multi select lookup column.

Normally in this scenario, the default values are loaded into the left-hand side of the look up with the right-hand "Responsibility selected values" being blank. What I want to do is to load the right-hand listbox with the values stored in array.

I am open to a solution which is based on both jQuery and JavaScript Client Object Model. I haven't been successful so far. :( Please help.

 var newarry = new Array();
 $("[title='System']").change(function() {
     var responsibilityval = "";
     if (newarry.length > 0) {
         $.each(newarry, function(i) {
             if (newarry[i] != '') {
                 alert(newarry[i]);
                 var mySelect = $("[title='Unit']");
                 mySelect.prepend("<option value='0'>Before Apples</option>");
             }
         });
     }
 });

I tried other options like but it didn't work

var mySelect = $("[title='Unit']");
mySelect.val(1)

Javascript object model sample

 function getWebSiteData() {
     clientContext = new SP.ClientContext.get_current();
     if (this.clientContext != undefined && clientContext != null) {

         var webSite = clientContext.get_web();
         oList = webSite.get_lists().getByTitle("Add New User");
         $.urlParam = function(name) {
             var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
             return results[1] || 0;
         }
         var itemid = parseInt($.urlParam('ID'));
         oListItem = oList.getItemById(itemid);
         var listinfo = new SP.ListItemCreationInformation();
         var item = oList.addItem(listinfo);
         var fields = ['Responsibility'];
         $(fields).each(function() {
             var fieldName = this;
             var field = $("#" + fieldName);
             var fieldValue = field.val();
             var entries = [];
             var newitem = new SP.FieldLookupValue();
             newitem.set_lookupId(1);

             entries.push(newitem);
             item.set_item(fieldName, entries);

         });
         item.update();
         oList.update();
         clientContext.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
     }
 }

 function success(sender, args) {
     alert('success');
 }

 function failed(sender, args) {
     alert("failed. Message:" + args.get_message());
 }
0

I use this function to set multi-select lookups

//Sets the default value(s) of a multi-select lookup
function SetMultiSelectLookup(fieldName, values)
{
    $.each(values, function(){
        $("select[title='" + fieldName + " possible values'] option:contains(" + this + ")")
                .remove()
                .appendTo($("select[title='" + fieldName + " selected values']"));
    });
    return false;   
}
0

I'm using SP OnPrem 2016 and this is working for me. The key is knowing how to set the hidden field that stores that values for the field.

The SetMultiSelectLookup function is totally generic.

In my case I am setting default Language Direction, so the values J>E means Japanese>English, etc. This is the Title field of my lookup list.

//setup default values where values = lookup id's
var defaultVals = [];
defaultVals.push(2);
defaultVals.push(3);

//call function to set multi valued lookup field
SetMultiSelectLookup('My Field Name', defaultVals);           

function SetMultiSelectLookup(fieldName, values){
        //add values to a multivalued select lookup field
        //fieldname = Title (display name) of the field
        //values = an array of lookup values, can be # or text
        try{
            var hiddenVal = '';
            //process each desired lookup value
            $.each(values, function(){
                //loop through all possible options and look for a match to the desired value
                var allOptions = $("select[title='" + fieldName + " possible values'] option");
                for (var i = 0; i < allOptions.length; i++) {
                    var currOption = allOptions[i];
                    //in this case 'this' is the # of the lookup value we passed in
                    if(currOption.value == this){
                        //add option to the selected values field
                        $("select[title='" + fieldName + " selected values']").append(currOption);
                        //setup value for hidden field, format:
                        //  2|tJ>E
                        //  1|tE>C|t3|tE>J    //add extra '|t' between entries
                        //  2|tJ>E|t1|tE>C|t3|tE>J    //add extra '|t' between entries
                        var newVal = currOption.value + '|t' + currOption.text;
                        if(hiddenVal == ''){
                            hiddenVal = newVal;
                        } else {
                            hiddenVal = hiddenVal + '|t' + newVal;  //insert extra '|t' between entries
                        };
                    };
                };
            });

            //add to hidden field that stores the values; if we don't do this then the record won't save
            if(hiddenVal != ''){
                //the hidden field starts with the fieldname without spaces and ends with _MultiLookup
                var hiddenFieldPrefix = fieldName.replace(/ /g, '');
                $("input[id^='" + hiddenFieldPrefix + "'][id$='_MultiLookup']").val(hiddenVal);
            };
            return;
       }
       catch(err){
            alert(err.message);
       };
};

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.