0

I am trying to create a navigation warning for unsaved data, but I am having trouble because the page that I am trying to check clears radio buttons. The way that the page clears them is by deleting the radio buttons and adding new ones. I do not know how to detect that using jQuery. I already have some code that detects changes in textboxes and it detects if the radio buttons have changed states but it doesn't work when they have been cleared. This is my jQuery:

var warnMessage = "You have unsaved changes on this page!";

$(document).ready(function() {

$('input:not(:button,:submit),textarea,select,:disabled').change(function () {
    window.onbeforeunload = function () {
        if (warnMessage != null) return warnMessage;
    }
});

  $('input:submit').click(function(e) {
      warnMessage = null;
  });

});

Is there a way to detect if document.add was used in the page?

braX
  • 11,506
  • 5
  • 20
  • 33
jakethecool1
  • 85
  • 1
  • 1
  • 8
  • What if you added an attribute such as `changed = "yes"` when the page clears your radio buttons and checked for that in your submit click function? When the radio buttons have yet to be cleared it's attribute could be `changed = "no"`. – Nicolas Jul 14 '14 at 14:42
  • I'm trying to make it dynamic that way I can include it on multiple pages without having to modify the original page. @AndyZee I have tried .on('change') and that didn't work. – jakethecool1 Jul 14 '14 at 14:50
  • 1
    This will help you http://stackoverflow.com/a/16225393/382809 – Poelinca Dorin Jul 14 '14 at 15:16

1 Answers1

0

You should use .on() function (http://api.jquery.com/on/) in this way:

var warnMessage = "You have unsaved changes on this page!";

$(document).ready(function() {

    $(document).on('change', 'input:not(:button,:submit),textarea,select,:disabled', function () {
        window.onbeforeunload = function () {
            if (warnMessage != null) return warnMessage;
        }
    });

    $(document).on('click', 'input:submit', function(e) {
        warnMessage = null;
    });
});

Note the following:

  1. You need to select with $ a parent element (f.i. the entire document) containing the elements you want to detect the change/click. Only inside the .on function you can specify those elements.
  2. Function .on() is available only in jQuery>=1.7: if you have a lower version (but greater than 1.3) you should use .live() function (http://api.jquery.com/live/).
Marco
  • 236
  • 1
  • 4
  • That works the same way as what I had before. It doesn't register that the radio buttons have been removed and added as new ones. – jakethecool1 Jul 14 '14 at 16:16