4

My below code for a JavaScript pop-up works very well for my Visualforce page. However, when I click on my save button I also receive the pop-up, which I don't want in my case.

How do I modify the below code so that it shows the pop-up when I click anywhere except my save button?

var evt = window.attachEvent || window.addEventListener;
var checkEvt = window.attachEvent ? 'onbeforeunload' : 'beforeunload';
evt(checkEvt, function(e) { 
    var msg = 'Are you sure you want to leave the page?';
    (e || window.event).returnValue = msg;
    return msg;
});
5

There is a blog post here, that suggests using variables to handle this, so you would only show the message when your variable is false. Clicking the save button would set this variable to true in order to bypass your message screen.

<apex:page standardController="Account">
<script language="javascript" type="text/javascript">              
    var tempDisableUnload = false;
    window.onbeforeunload = function() {
        if(!tempDisableUnload){
            return confirm("You have made changes to this form. Do you want to continue without saving these changes?");
        }
        return;

    }    
    function setDisableUnload() {
        tempDisableUnload = true;
    }                             
</script>  
<apex:form >
    <apex:pageBlock>
        <apex:commandButton value="Save" action="{!save}" onclick="setDisableUnload();"/>
        <apex:inputText value="{!Account.external_id__c}"/>
    </apex:pageBlock>
</apex:form>

4
  • this is not working at all..i have pasted the same code in my script tags.. :(
    – Neha Patil
    Nov 19 '14 at 4:12
  • @NehaPatil I edited answer with code that I tested out on my Dev org and this is working for me.
    – Jenny B
    Nov 20 '14 at 1:54
  • i dont know why its not working for me..i tried the same code :(
    – Neha Patil
    Nov 26 '14 at 4:22
  • @NehaPatil Which part doesn't work? What browser are you using?
    – Jenny B
    Nov 26 '14 at 11:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.