How To Set Alert Message When An Incomplete Filled Form Is Closed.

Hello everyone.

I have a simple create new post form, in which we can enter the new post data, now I want that when entering the data in post and the form is not yet filled completely, so at that time if the user press back button in browser, or want to close the browser then the there should be some alert that wether you want to save the entered data before close or not save the data etc,

So how can I do this ??

Thanks in Advance.

You need to use the onbeforeunload event handler.

In jQuery, I suspect you would use something like this:




var fieldsChanged = false;


$(window).on('beforeunload', function(){

    if (fieldsChanged)

        return 'You have unsaved changes, are you sure you wish to leave this page?';

});



You’d need to use another event handler to capture changes to the form inputs and set the fieldsChanged variable to true. Perhaps:




$('body').on('change', '#formId :input', function(){

    fieldsChanged = true;

});



should I use both events in the same file ?

Yep, I’d order them like this:




var fieldsChanged = false;


$('body').on('change', '#formId :input', function(){

    fieldsChanged = true;

});


$(window).on('beforeunload', function(){

    if (fieldsChanged)

        return 'You have unsaved changes, are you sure you wish to leave this page?';

});



1 Like

You could make a more general solution by putting something like this in your main JavaScript file:




var protectedFormChanged = false;


$('body').on('change', 'form.warn-lose-changes :input', function(){

    protectedFormChanged = true;

});


$(window).on('beforeunload', function(){

    if (protectedFormChanged)

        return 'You have unsaved changes, are you sure you wish to leave this page?';

});



Now, you can add the class ‘warn-lose-changes’ to any form and the warning will happen automatically without any JavaScript code in the view.

thanks a lot sir.