Question

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

Was it helpful?

Solution

Use this;

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

OTHER TIPS

If you want to exclude an element from selector, you can use :not().

$('form *:not(input[name="photo"])').change(function(){
    formmodified = 1;
});

Or with function:

$('form *').not('input[name="photo"]').change(function(){
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top