Last Updated: February 25, 2016
·
7.955K
· 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?'
    }
})

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside