2

I have a modal dialog in my App that contains about 10 inputs (i.e. text, dates, number and select inputs). I need know if value of any of the widget changed by the user, so that when they click on the cancel button I can prompt them if they like to save changes before closing the dialogue window.

I can do this in two ways, which may not be the smartest way:

1) set a global variable in my javaScript and keep track in "onChange" event.

2) Compare the value of each widget or inputs before and after to determine if any of them changed.

I wonder if there are any other options that I am not aware of since I am new to jQuery and javaScript.

I apologize if this a duplicate question, I searched and found another similar issue but not what I am after. Best way to track onchange as-you-type in input type="text"?

Thanks

Community
  • 1
  • 1
PK-Albany
  • 23
  • 4

1 Answers1

2

Use a dirty flag:

var dirty = false;
$('#myModalForm input').change(function() {
  dirty = true;
});
$('#myModalForm #cancelButton').click(function() {
  if (dirty) {
    //confirm
  }
  // exit modal
});
$('#myModalForm #save').click(function() {
  // save
  dirty = false;
});
SomeKittens
  • 38,868
  • 19
  • 114
  • 143
  • @SomeKittens_Ux2666 thanks for your example. This is much better than what I was doing. It worked for all form fields except "Select/Option" fields. So I just added following: $('#myModalForm select').change(function() { dirty = true; }); – PK-Albany May 02 '14 at 15:56
  • // One more thing to add is when user is not saving then set the variable to false so that user can open the dialogue again if (dirty) { //confirm if (confirm("Do not save?")) dirty = false; } // exit modal – PK-Albany May 02 '14 at 16:03