Pages

October 4, 2018

Fix limited width of lookup fields in SharePoint forms

Ever had pain seeing the full text contents of a lookup field while editing an item in SharePoint? if the answer is yes then you are not alone.
The problem with lookup field controls that allow multiple values is that when items are long, the field box will not adjust itself to show all content as it has a fixed width which hinders the display of a long item.The user has to hover the item to show a tool tip with item title. Imagine doing this for many items!
The thing is the lookup field control is the same old one from SharePoint 2007 era and the UI part of it was not updated in subsequent versions.

Here is what's currently offered by default:
Right before adding any items:
While adding items:
 

From inspecting any SharePoint page that has a lookup field (with 'allow mutliple values'), the control's html should look like this:
<select
name="{wpGuid}SelectCandidate"
title="{Title}"
id="{wpGuid}_SelectCandidate"
style="width: 243px; height: 125px; overflow: auto;"
ondblclick="..."
onchange="..."
multiple="multiple">
<option title="{Option1Title}" value="{Option1Value}">{Option1Title}</option>
<option title="{Option2Title}" value="{Option2Value}">{Option2Title}</option>
<option title="{Option3Title}" value="{Option3Value}">{Option3Title}</option>
...
..
.               
</select>


Solution
The idea is to write a lightweight script to wait for page load, then get all elements where ID contains the phrase "SelectCandidate", and replace the style to remove the 'width' parameter. This will be affect all lookup fields in that page. If no items where selected in that field, it will shrink to minimum width, and when items are added it will expand to the width of the longest item. The result is it will show all contents clearly.


Right before adding any items:
While adding items:


Steps
Do the following for target lists or libraries where you used 1 or more lookup columns with 'allow multiple values' option.

1) Edit NewForm.aspx or EditForm.aspx

2) Add a script editor AFTER the default item view web part

Title:
"Dynamic lookup field width script"

Contents:
<script>
$(document).ready(function () {
$("select[id*=Select]").each(function(){
$(this).attr('style', function(i, style)
{
    return style && style.replace(/width[^;]+;?/g, '');
});
});
});
</script>


 3) Save form!