Search code examples
jqueryonbeforeunload

Display alert if conditions are met, almost like onbeforeunload


I have a form broken into 5 steps. Currently if you refresh/exit/close etc on steps 2-4 it returns a message via window.onbeforeunload no issues there.

window.onbeforeunload = function () {
            if ( $("#step1").is(":visible") || $("#step2").is(":visible") || $("#step3").is(":visible") ) {
                return 'Using the browsers back, refresh or close button will cause you to lose all form data. Please use the Next and Back buttons on the form.';
            }
        }

Now I need to add the same or similar type of behavior on step0 (first step) if checkbox "A" is checked and checkbox "B" isn't. This works, but not combined with another .onbeforeunload function

window.onbeforeunload = function () {
            if ( $("#A").is(":checked") && $("#B").is(":not(:checked)") ) {
                return 'Message here. Do you wish to continue?';
            }
        }

How can I chain these two together? using an if, else statement doesn't seem to work.


Solution

  • You can combine them in one function like this:

    window.onbeforeunload = function () {
      if ( $("#A").is(":checked") && !$("#B").is(":checked") ) {
          return 'Message here. Do you wish to continue?';
      }
      if ( $("#step1, #step2, #step3").filter(":visible").length) {
          return 'Using the browsers back, refresh or close button will cause you to lose all form data. Please use the Next and Back buttons on the form.';
      }
    }
    

    I simplified your other selector to grab all elements, .filter() only :visible ones and see if there are any (.length > 0), this is just an easier-to-maintain way of going about it.

    Also you may want to add an additional check to the first if, ensure you're on that step, like this:

    if ($('#step0').is(':visible') && $("#A").is(":checked") && !$("#B").is(":checked") ) {