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.
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.
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".
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.