Search code examples
jqueryjquery-selectorsonbeforeunload

Chain .on() with .not() to remove unneeded elements from the object


I have a web form, that I bind the beforeunload event to the window to detect any changes to the form except the inputs that I do not need to include. So for example, an input that I don't need to bind the beforeunload event. It should only bind for inputs that will affect losing changes when navigating away from the window.

This is the current binding I have:

formChanged = false;
$('#main-form').on('change.form_change', 'input:not(.leave-change-allowed), textarea:not(.leave-change-allowed), select:not(.leave-change-allowed)', function()
{
    if(!formChanged)
    {
        formChanged = true;

        $(window).bind('beforeunload', function()
        {
            if(formChanged)
            {
                return 'Are you sure you want to navigate away from this window, you will lose unsaved changes.';
            }
        });
    }
    else
    {
        $(this).unbind('change.form_change');   
    }
});

As you can see I have included :not(.leave-change-allowed) to the elements in the selector, separated by commas to select the form elements. Although, I don't want to add the not() to the selector, because there may be few selectors I want to add to the not(), but I would need to apply to each form inputs input, textarea and select. Please bear in mind that these elements are dynamic, so I used .on() rather than .change().

How can I chain the .not() function with the dynamic elements? So I keep the selector intact, and pass all the unnecessary elements in the .not() function?


Solution

  • Check the target for the class inside the function :

    formChanged = false;
    $('#main-form').on('change.form_change', 'input, textarea, select', function(e) {
        if(! (formChanged || $(e.target).is('.leave-change-allowed')) ) {
            formChanged = true;
            $(window).on('beforeunload', function() {
                if(formChanged) {
                    return 'Are you sure you want to navigate away from this window, you will lose unsaved changes.';
                }
            });
        } else {
            $(this).off('change.form_change');   
        }
    });