You can create a pop-up that asks the user if he is sure that he wants to leave the page. This is used on Gmail, Facebook, Twitter, Stackoverflow, LinkedIn, etc., in all pages where you might lose data, if you accidentally close the tab.

The most basic example is this:


$(window).bind('beforeunload', function(e){
       return true;
 });

This would fire always a warning when the user tries to leave the page. This is of course very unfriendly. Assume we have multiple textboxes like this:

and the textboxes are of the form


<textarea name="comment[1]"></texarea>
<textarea name="comment[2]"></texarea>
<textarea name="comment[3]"></texarea>
<textarea name="comment[4]"></texarea>

and we want to warn the user, whenever he changes text in a textarea without saving it. First we need a function that saves the current status on page load of all the textareas. Something like this:


  function saveComments(){
        $('textarea[name^=comment]').each(function(){
            $(this).data('comment', $(this).val());
        });
  }

  $(document).ready(function(){
    saveComments();
  }

Then we have to check if the content has changed whenever the user leaves:


  $(window).bind('beforeunload', function(e){
          var $issue = false;

          $('textarea[name^=comment]').each(function(){
              if($(this).val() != $(this).data('comment')){
                $issue = true;
              }
          });

          if($issue){
            return true;
          }
      });

Some notes on that one:

  • You can't adjust the confirm message. There is no difference betweent returning a string or a boolean. It was possible a long time ago, but not anymore duo to scam abuses.
  • Note that the return needs to be outside of the each function.
  • Alert does not work inside the bind function. But you may use console.log

Finally, you need to store the content of each textarea whenever the user presses one of your save buttons.

 
  $('.save').click(function(e){
    e.preventDefault();

    //make sure to save the content.
    saveComments();

    // and then do ajax call or whatever you want ;)
    $bemerkungen =   $('textarea[name^="comment"]').serialize();
    $.ajax({
      type: "POST",
      url: '/admin/comments/save',
      data: $bemerkungen
    })

Leave a comment

Your email address will not be published. Required fields are marked *