Skip to content

Instantly share code, notes, and snippets.

@tentacode
Created May 22, 2014 08:21
Show Gist options
  • Select an option

  • Save tentacode/fc6a4646b9140e02dfdf to your computer and use it in GitHub Desktop.

Select an option

Save tentacode/fc6a4646b9140e02dfdf to your computer and use it in GitHub Desktop.

Revisions

  1. Gabriel Pillet created this gist May 22, 2014.
    3 changes: 3 additions & 0 deletions form.html
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,3 @@
    <form action="..." data-unsaved-warning>
    <!-- Something something the form -->
    </form>
    27 changes: 27 additions & 0 deletions unsaved-changes.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    $(document).ready(function() {
    $('body').on(
    'change',
    'form[data-unsaved-warning] select, form[data-unsaved-warning] input, form[data-unsaved-warning] textarea',
    function(e) {
    $(e.target).parents('form').attr('data-unsaved-changes', '1');
    }
    );

    $('body').on('submit', 'form[data-unsaved-warning]', function(e){
    $(e.target).data('submitting', '1');
    $(e.target).data('unsaved-changes', '0');
    })

    $(window).bind('beforeunload', function(e){
    var error = '';
    $('form[data-unsaved-changes="1"]').each(function(i, form) {
    if ($(form).data('submitting') !== '1') {
    error = "Warning : you did not save your form !";
    }
    })

    if (error != '') {
    return error;
    }
    });
    });