JavaScript to Conditionally Enable a SharePoint Custom Ribbon Button

During my session on getting started with apps for SharePoint 2013, I demonstrate how to use the “extension” app shape to define a UI custom action that displays a button in the ribbon. When clicked, this button allows the user to view a Bing traffic map centered at the location specified in the selected list item. This is done using a CustomAction in the same declarative manner as it was done in SharePoint 2010, using the following XML:

customaction1

Installing the app adds a button labeled “Plot on Bing Traffic Map” to the “Items” tab on all custom lists in the host web where the app is installed:

button0

In my CommandAction of the CommandUIHandler for the CommandUIExtension I define to create the button, I specify that clicking the button will take the user to the following URL:

~appWebUrl/Pages/BingTrafficMap.html?{StandardTokens}&ListID={ListId}&ItemID={SelectedItemId}

Note the use of the SelectedItemId token in the URL above. This means my BingTrafficMap.html page can rightly expect to have an ItemID parameter in its query string, which can then be parsed to get the list item and read its properties using JavaScript.

But what if the user hasn’t selected any items? Or multiple items? Since I can only center a map on one single location, I need to have more control over when this button is enabled. In this case, I only want the button to be enabled when exactly one item in the list is selected. (By default, any ribbon buttons you create through custom actions will always be enabled, regardless of whether or not any items are selected.)

As it turns out, there is an EnabledScript attribute of the CommandUIHandler that will enable or disable the button depending on whether the function returns true or false. I was able to adapt this code from Tomasz Rabiński to add the following logic to my CommandUIHandler:

customaction2

Note that the function EnableDisable–which I can define and then call within the EnabledScript attribute–returns true only if the number of selected items equals 1.

Now my button behaves exactly as I would expect.

No items selected (disabled):

button1

One item selected (enabled):

button2

More than one item selected (disabled):

button3

I have updated my demo code to include this change. You can download this code here.