views:

58

answers:

2

Could you recommend some lightweight jQuery plugin to detect if fields specified by selector have changed?

E.g. like this one on SO, showing confirmation dialog when I want to reload page during post edition.

+1  A: 

No plugin is necessary:

$('selector').change( function() { alert( 'I've changed!'); } );

The one on SO is different, it is checking to see if a box is empty or has the default text in it before you do an action. It isn't being triggered "on change".

Kerry
I don't think that's what he's referring to. The confirm dialog only pops up when you type something into the "Ask Question" or "Your Answer" box and try to leave or refresh the page.That is done without any kind of AJAX request and probably just checks to see if those fields are non-empty.
Lèse majesté
Ahh, thank you, updated last paragraph.
Kerry
+3  A: 

This is too basic/specific a functionality to likely have its own plugin.

All you need to do is store a boolean value that gets set to true if any element is changed:

var changed = false;

$(document).ready(function() {
    $('.watch-for-changes').change(function() {
        change();
    });
    window.onbeforeunload = function() {
        if (hasChanged()) {
            return "There are unsaved changes on the page.";
        }
    };
}

function change() {
    changed = true;
}

// use this to programmatically change an input field
function changeValue(elField, value) {
    $(elField).val(value);
    change();
}

function hasChanged() {
    return changed;
}

Edit: previous use of onbeforeunload was incorrect. See this page for more details on its usage.

Lèse majesté