David Wolever
David Wolever

Reputation: 154484

HTML: listen for *all* changes to an input, not just keyboard-driven changes?

For example, if I've got an input like this:

<input id="myInput" type="text" />

How can I be notified when the value is changed programatically (for example, as a result of $("#myInput").val("new value"))?

An example: http://jsfiddle.net/2ax9y/

Edit: please note, the question is asking how to listen for changes, not “how to manually dispatch changes”. I'm well aware that I can manually dispatch change events, but I'm trying to avoid that.

Upvotes: 3

Views: 985

Answers (4)

jzila
jzila

Reputation: 735

You can change the $ prototype to always trigger change() events whenever val(value) is called:

$.prototype.changeval = $.prototype.val;
$.prototype.val = function(v) {
    if (v) {
        $(this).changeval(v);
        $(this).change();
    } else {
        return $(this).changeval();
    }
}

Upvotes: 2

shazow
shazow

Reputation: 18157

You can't reliably subscribe to every change on an input element, but you can check if there has been a change since you last checked and do that within some desired time granularity.

Make a checker function and loop it with your desired time granularity—100ms is a good start, adjust to your needs.

Hypothetical untested implementation:

var last_value = null;

function handle_changed() {
    // Do something here
}

function check_value() {
    var v = $("#myelement").val();
    if(v !== last_value) {
        last_value = v;
        handle_changed();
    }
}

setInterval(check_value, 100);

Upvotes: 1

Joseph Marikle
Joseph Marikle

Reputation: 78520

I don't think this is an inherent ability of the change event. You could manually trigger the change event when you programmatically change the value.

$("#myInput").val(+(new Date())).change();

Upvotes: 0

Naftali
Naftali

Reputation: 146302

Trigger the change: http://jsfiddle.net/maniator/2ax9y/1/


A little differently: http://jsfiddle.net/maniator/2ax9y/2/

Upvotes: 1

Related Questions