Thursday, September 11, 2014

Select all items in a MultiLookupPicker

I had a client that wanted all options in a multi-select lookup field to be selected when a new item was created

Then the user could deselect what they did not need, more common to need all. Well it turns out you can't specify the default values for a multi-lookup field.

I came across this post from Bil Simser (thanks) that gave me the ideas for this JavaScript function to select all the possible options in a specific MultiLookupPicker item.  The argument is the name of the field you want to select from, there could be more than one on the page.

jQuery.fn.exists = function () {
    return this.length !== 0;

SD.SP2010.MultiLookupPicker.SelectAll = function(pickerTitle) {
    if (jQuery("[id$='_SelectCandidate'][title^='" + pickerTitle + "']").exists()) {
        // append the new options to our results (this updates the display only of the second list box)
        jQuery("[id$='_SelectCandidate'][title^='" + pickerTitle + "']").children().detach().appendTo("[id$='_SelectResult'][title^='" + pickerTitle + "']");
        var data = jQuery("[id$='_SelectCandidate'][title^='" + pickerTitle + "']").closest("table").siblings("[id$='MultiLookupPicker_data']").val();
        data = data.replace( /\|t \|t /g , "");
        // append the new options to our hidden field (this sets the values into the list item when saving)   
        jQuery("[id$='_SelectCandidate'][title^='" + pickerTitle + "']").closest("table").siblings("[id$='MultiLookupPicker']").val(data);