jQuery - Detect value change on hidden input field jQuery - Detect value change on hidden input field jquery jquery

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 trackingtrackChange( $("input[name=foo]")[0] );


You can simply use the below function, You can also change the type element.

 $("input[type=hidden]").bind("change", function() {       alert($(this).val());  });

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.

HTML

 <div id="message"></div><input type="hidden" id="testChange" value="0"  />    

JAVASCRIPT

var $message = $('#message');var $testChange = $('#testChange');var i = 1;function updateChange() {    $message.html($message.html() + '<p>Changed to ' + $testChange.val() + '</p>');}$testChange.on('change', updateChange);setInterval(function() {    $testChange.val(++i).trigger('change');;     console.log("value changed" +$testChange.val());}, 3000);updateChange();

should work as expected.

http://jsfiddle.net/7CM6k/3/