views:

27

answers:

3

can I use blur in a hidden field in jquery? if not, how can I track changes in a hidden field

+2  A: 

Hidden field is hidden, it won't be visible to a user to change something. Only page author/script can change its value and if that is the case, you can use the change event to track changes.

$('#hidden_id').change(function(){
  alert('Changed Value: ' + $(this).val());
});
Sarfraz
a quick test shows that this is [not working](http://jsfiddle.net/3BrxY/) ;)
Reigel
@Reigel: That's because programatically changing the value of an input does not fire the change event. Which is why I always write it like `$('#elem').val(new_val).trigger('change')`. http://jsfiddle.net/nS4Jt/1/
Mark
@Mark - that was my point. ;)
Reigel
@Reigel: He will have to trigger change event explicitly like @Mark commented.
Sarfraz
@Reigel: Yes, but you didn't explain *why* or how to fix it ;)
Mark
A: 

NO, you can't in it's normal behavior.

The onchange event occurs when a control loses the input focus (blur) and its value has been modified since gaining focus.

http://www.w3.org/TR/html401/interact/scripts.html#adef-onchange

But you can do it as Sarfraz suggested. Add onchange event then explicitly trigger it every time you change the value of the hidden typed input

Reigel
A: 

The 'change()' event handler doesn't work on hidden input fields. What you can do instead is something along these lines (untested!):

function hiddenOnChange(elem, function) {
    if ($(elem).val()!=$(elem).getAttr('oldVal')) {
        function;
    }
    $(elem).attr('oldVal', $(elem).val());

    window.setTimeout(function(){hiddenOnchange(elem, function);}, 100);
}

Call this function with your hidden input field and the onchange function. It re-creates the onchange function by comparing the field's "current" value with a previously stored value. If nothing is changed, it re-checks in 100 msecs; If something did change, it will execute your function (I hope ;))

Hope this helps.

Edward