Eckstein Eckstein - 4 years ago 86
Javascript Question

Detecting if form has changed, script not working

I am trying to use the following script to detect if any fields in my form have changed (edit: detect if the values of my form fields have changed), and alert the user if so. Otherwise, another js box is displayed.

It's not detecting any changes though, and the confirm box is never shown. What am I doing wrong?

$('#eventMedia').click(function() {
var form_changed = false;

$('#tribe-events > form').on('keyup change', 'input, select, textarea', function(){
form_changed = true;
});

if (form_changed == true) {
confirm('You have unsaved changes! Click Cancel to save your changes before continuing.');
} else {
$('#eventMediaBox').show();
$('#blackFade').show();
}
});

Answer Source

You're starting to register keyup and change events only once the #eventMedia button is clicked which is probably not the desired order of things.

instead:

// Set the boolean flag variable first
var form_changed = false;

// On `input change` events - set flag to truthy
$('#tribe-events > form').on('input change', 'input, select, textarea', function(){
    form_changed = true;
});

// Showtime!
$('#eventMedia').click(function() {
    if (form_changed) {
        alert('You have unsaved changes! Save your changes before continuing.');
    } else {
        $('#eventMediaBox, #blackFade').show();
    }
});

Notice that the "input" event (in .on('input change') will also cover the cases where the user pastes content using mouse etc...

Also, don't forget to reset sometimes your form_changed back to false in your code...

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download