Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exit confirm function and removing the function on submit with javascript and jQuery

I want to be able to allow the user to confirm if they want to leave the page if they don't want to submit the form.
However, I DONT want this function to work on the submit button. When the user clicks submit, I don't want them to be confused with an exit confirmation.
The id concerned is #publishbtn and I'm trying to use the .off method.
The script is on the bottom of the page
Not sure if this is an issue.

<%= f.submit "PUBLISH", :class => "greenbtn extrayo", :id => "publishbtn" %>


<script type="text/javascript">
  window.onbeforeunload = confirmExit;
  function confirmExit()
  {
    return "Ready to move on? Or you wanna leave?";
  }
  $( "#publishbtn" ).click(function() {
  $( "body" )
    .off( "click", "#publishbtn", confirmExit )
    .find( "#publishbtn" )
      .text( "Put into" );
});
</script>
like image 644
Rick G Avatar asked Aug 13 '26 11:08

Rick G


1 Answers

Use window.onbeforeunload = null to remove the listener. To remove it on form submit you could use something like this:

$('#someForm').on('submit', function (event) {
    window.onbeforeunload = null;
});

Where someForm is id of your <form> element.

like image 96
Andrew Surzhynskyi Avatar answered Aug 15 '26 04:08

Andrew Surzhynskyi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!