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:
style="width: 243px; height: 125px; overflow: auto;"
<option title="{Option1Title}" value="{Option1Value}">{Option1Title}</option>
<option title="{Option2Title}" value="{Option2Value}">{Option2Title}</option>
<option title="{Option3Title}" value="{Option3Value}">{Option3Title}</option>

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:

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

"Dynamic lookup field width script"

$(document).ready(function () {
$(this).attr('style', function(i, style)
    return style && style.replace(/width[^;]+;?/g, '');

 3) Save form!