Skip to content Skip to sidebar Skip to footer

Adding Text Change Listener To A Text Box

I am trying to add a text change listener to a text box. However, the text is not only changed manually by entering the text. For that I can just use the keyup listener. Actually,

Solution 1:

Depending on the Browsers you need to support you might use HTML5's oninput. It fires immediately when the monitored input changes. In jQuery you would just do:

$('#my-input').bind('input', function(e) {
    console.log("#my-input's value changed");
});

Update: Unfortunately this method won't work as the event doesn't fire on scripted changes of the input's value. You will have to hook into your calender "manually" just like OverZealous mentioned.

Solution 2:

How instant do you need this change to occur? Because (despite feeling dirty even writing this), you might be able to poll the field for changes, like this:

functionwatchField(fieldId, callback) {
    var previousVal = null;

    returnsetInterval(function() {

        var field = document.getElementById(fieldId);
        var newValue = field.value;

        if(previousVal !== null && previousVal != newValue) {
            callback(fieldId, newValue, previousVal);
        }
        previousVal = newValue;

    }, 2000); // check every 2 seconds
};

var cancelListeneId = watchField("myField", function(field, newValue, previousValue) {
    // handle change
});

// to cancel listener// clearInterval(cancelListenerId);

Only use this if there is no better solution!

This is horrible, awful, and just plain wrong. I should downvote myself. But it might work. ;-)

Post a Comment for "Adding Text Change Listener To A Text Box"