jQuery - Detect value change on hidden input field
So this is way late, but I've discovered an answer, in case it becomes useful to anyone who comes across this thread.
Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.
function setUserID(myValue) {
$('#userid').val(myValue)
.trigger('change');
}
Once that's the case,
$('#userid').change(function(){
//fire your ajax call
})
should work as expected.
Since hidden input does not trigger "change" event on change, I used MutationObserver to trigger this instead.
(Sometimes hidden input value changes are done by some other scripts you can't modify)
This does not work in IE10 and below
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var trackChange = function(element) {
var observer = new MutationObserver(function(mutations, observer) {
if(mutations[0].attributeName == "value") {
$(element).trigger("change");
}
});
observer.observe(element, {
attributes: true
});
}
// Just pass an element to the function to start tracking
trackChange( $("input[name=foo]")[0] );