Last Updated: February 25, 2016
·
7.374K
· gearheart

Alert when leaving page with unsaved form

The task is to show alert message like "Are you sure you want to leave this page" when user changed some data in form, but haven't submit it.

Here is a quick'n'dirty way to make it with jQuery:

$(document).ready(function(){
    var form = $('#some-form'),
        original = form.serialize()

    form.submit(function(){
        window.onbeforeunload = null
    })

    window.onbeforeunload = function(){
        if (form.serialize() != original)
            return 'Are you sure you want to leave?'
    }
})