I started with Vikars answer, but noticed too that when the hidden form fields used in a HTML form that the last changes didn't get submited. Later on I found Thomas answer, so I combined both to the following solution, which seems to work nicely for my hidden form fields also on submit:
function replaceWithWrapper(selector, property, callback) {
function findDescriptor(obj, prop){
if (obj != null){
return Object.hasOwnProperty.call(obj, prop)?
Object.getOwnPropertyDescriptor(obj, prop):
findDescriptor(Object.getPrototypeOf(obj), prop);
}
}
jQuery(selector).each(function(idx, obj) {
var {get, set} = findDescriptor(obj, property);
Object.defineProperty(obj, property, {
configurable: true,
enumerable: true,
get() { //overwrite getter
var v = get.call(this); //call the original getter
//console.log("get '+property+':", v, this);
return v;
},
set(v) { //same for setter
//console.log("set '+property+':", v, this);
set.call(this, v);
callback(obj, property, v)
}
});
});
}
replaceWithWrapper('#myhiddenfield', 'value', function() {
console.log('myhiddenfield value changed!');
});