Cyril Cyril - 4 months ago 27
jQuery Question

SharePoint 2013 - save button in the ribbon - cancel saving if form not valid

I want to perform some validation when a user click the save button on the SharePoint ribbon and cancel the submission of the form if it is not valid.

I am using a page layout in SharePoint 2013. The fields come from the page layout content type.

The id of the button is Ribbon.EditingTools.CPEditTab.EditAndCheckout.SaveEdit-SelectedItem

I tried without success:


  • add an onclick handler on the button

    var saveButton = function () {
    return document.getElementById("Ribbon.EditingTools.CPEditTab.EditAndCheckout.SaveEdit-SelectedItem");
    }
    $(saveButton()).removeAttr("onclick");
    $(saveButton()).click(
    function(ev){
    ev.preventDefault();
    ev.returnvalue=false; // for IE only
    return false;
    }
    );

  • replace the onsubmit attribute of the form

    $("form").attr("onsubmit","javascript: return false;")



Both codes are happily ignored by sp2013!

Answer

To cancel the event, instead of targeting the link, I have targeted the img inside the link. My javascript code is then fired before the SharePoint javascript.

$("#Ribbon\\.EditingTools\\.CPEditTab\\.EditAndCheckout\\.SaveEdit-SelectedItem img").click(function(){
    console.log("saveButton clicked");
    return false;
});

The double antislashes are meant to tell jquery this is no class name but a dot in the id.

Another problem arised: the save button can take a few seconds to load, so we have to wait before attaching the click handler. Finally the code is like this:

//namespace
var qp = {}
// attaching a click handler to the save button image
qp.registerSaveButtonEvent = function() {
    var b = "#Ribbon\\.EditingTools\\.CPEditTab\\.EditAndCheckout\\.SaveEdit-SelectedItem img";
    // if the button exists
    if ($(b).length > 0) {
        // we attach the click handler to it
        $(b).click(function(){
            console.log("saveButton clicked");
            return false;
        });
        // we stop the future calls of this function
        clearInterval(qp.interval);
    }
}
// Running the function every 500 ms
qp.interval = setInterval(qp.registerSaveButtonEvent, 500);