0

I assign the element id "btn_submit" to write_ok button.

I wanted the following:

if I press write_ok button,
  do write,
else (if I do not press write_ok button)
  do alert message before page exit.

I don't know how can i find out which button was pressed.

I found this, but I cannot get it to work: jQuery: how to get which button was clicked upon form submission?

<script type="text/javascript">
$(window).bind('beforeunload', function(){
    if ( #btn_submit was not pressed )
        return 'If you exit the page, you may lose your changes';
});
</script>
Community
  • 1
  • 1
OpenCode
  • 315
  • 7
  • 19

3 Answers3

1

You can do something like,

<script type="text/javascript">
  var btn_submit_pressed = false;

  $(window).bind('beforeunload', function(){
      if ( btn_submit_pressed )
          return 'If you want to exit page, you may lost your writing';
  });

  $('#btn_submit').click(function(){ btn_submit_pressed=true; });

</script>
Abhijeet Pawar
  • 690
  • 6
  • 19
  • WOW~!!! Great~!!! ` ` – OpenCode Mar 02 '12 at 19:12
0

You could introduce a variable:

var isSaved = true;  // at the beginning there's nothing unsaved

Whenever the user updates something, set:

isSaved = false;

When the user clicks submit, set:

isSaved = true;

Then in beforeunload, just check:

if(!isSaved) {
pimvdb
  • 151,816
  • 78
  • 307
  • 352
  • thanks for your reply. if i add variale, i must do many works. – OpenCode Mar 02 '12 at 18:27
  • @OpenCode: Not sure I understand. This should be pretty trivial; you shouldn't need to add more than these 4 lines of code. – pimvdb Mar 02 '12 at 18:28
  • i just want to do like this, http://stackoverflow.com/questions/5721724/jquery-how-to-get-which-button-was-clicked-upon-form-submission – OpenCode Mar 02 '12 at 18:38
  • my test code is...`` – OpenCode Mar 02 '12 at 18:41
0

Pawar's code is a big idea. to compress and generize the code, #btn_submit changed to "input submit".

message in return is appear only IE not firefox, chrome.

<script type="text/javascript"> 
  var btn_submit_pressed = true; 
  $(window).bind('beforeunload', function(){ 
  if ( btn_submit_pressed ) 
        return 'if you leave this page, chages will be lost.'; 
  }); 
  $('#btn_submit').click(function(){ btn_submit_pressed=false; }); 
</script>
OpenCode
  • 315
  • 7
  • 19