Prompt User For Unsaved Activity Using Javascript

In this article you will learn how to prompt a user for unsaved activity, using JavaScript.

Hello Friends,

While working on a large form with many text boxes and dropdowns, I felt a need to provide a confirmation message that could prevent the loss of information due to an accidental click elsewhere. So I thought I should share the solution with you, hoping it might help someone.

Say you want the user to be prompted when he/she has some unsaved activity on the page. You can use the window.onbeforeunload event for this.

Add this in the .aspx page head:

<script type="text/javascript">
window.onbeforeunload = function(e) {
var message = \"You have not saved your changes. Do you wish to leave and abandon your changes or stay on this page so you can save?\";
e = e || window.event;
if (e) {
e.returnValue = message;
return message;}
function CheckUnSavedChanges(form) {
    for (var i = 0; i < form.elements.length; i++) {
        var element = form.elements[i];
        var type = element.type;
        if (type == "checkbox" || type == "radio") {
            if (element.checked != element.defaultChecked) {
                    return true;
        else if (type == "text" || type == "textarea") {
            if (element.value != element.defaultValue) {
                return true;
        else if (type == "select-one" || type == "select-multiple") {
            for (var j = 0; j < element.options.length; j++) {
                if (element.options[j].selected != element.options[j].defaultSelected) {
                    return true;
    return false;

The function "CheckUnSavedChanges" checks every checkbox, radio button, text box, text area and dropdown to see whether there is any change made before leaving the page and if changes have been made then it will prompt for confirmation with a confirmation box.

Here is how it will look:


Hope that will help someone.