Introduction
We can create our own custom button and add it to top ribbon menu. On selection of any content items from the list, we will execute some functionality on selected items from custom button click. But what happens if user does not select any of items from the list and click on ribbon button. In this case we will get the selected items as null and can not proceed further.
So in order to enable or disable the custom ribbon button, we can have some java script code which will tell us whether user has selected any of items or not. We can map this JavaScript code to EnabledScript property of CommandUIHandler.
From Custom Ribbon Button.xml
<CommandUIHandlers>
<CommandUIHandler
Command="CustomRibbon_Command"
CommandAction="javascript:CustomRibbonButtonClick();" EnabledScript="javascript:EnableDisableRibbonButton();" />
</CommandUIHandlers>
<CustomAction Scriptsrc="/_layouts/15/CustomRibbon/js/External.js" Location="ScriptLink" Sequence="2" />
If you observe, we have registered an external JavaScript file(External.js) which has two JavaScript functions CustomRibbonButtonClick and EnableDisableRibbonButton.
JavaScript Code to Enable/Disable Ribbon Button:
The below function returns true if the selected item count is 1 or else it returns false.
function EnableDisableRibbonButton()
{
var currentClientContext = SP.ClientContext.get_current();
var selectedItems = SP.ListOperation.Selection.getSelectedItems();
var count = CountDictionary(selectedItems);
if (count == 1) {
return true;
}
return false;
}
function CustomRibbonButtonClick()
{
alert('success');
}
Note: - By default ribbon button will be disabled mode.
- CustomRibbonButtonClick will be invoked when the custom ribbon button is in enabled mode and user is clicked on it.