Search code examples
javascriptjqueryformsonclickonbeforeunload

Avoid a form field when alerting the user is leaving the page without saving form changes


Hi all,

The following code warns the user that he/she has not submitted form changes when he/she tries to leave the webpage without clicking the submit button.

 formmodified = 0;
    $('form *').change(function(){
        formmodified = 1;
    });
    window.onbeforeunload = confirmExit;
    function confirmExit() {
        if (formmodified == 1) 
        {
            return "You need to save your changes before you leave the page";
        }
    }
    $("input[name='btnPost']").click(function() 
    {
        formmodified = 0;
    });

It works great, but I need this code to forget about a field in the form.

The field is this one a photo file uploader:

<input type="file" name="photo">

With the code as it is, the message alerting you are leaving the page shows before filling the rest of the form and it is quite confusing for the users that's why I need this field to be avoided.

Thanks a lot


Solution

  • Use this;

    $('form *').change(function(){
        if ($(this).attr("name") != "photo") {
          formmodified = 1;
        }
    });