最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Adding text change listener to a text box - Stack Overflow

programmeradmin2浏览0评论

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, the text field is for the date and I have a calendar which can be used to select the date and populate the text field. Now whenever there is a change in the text field I want to trigger an action. So which kind of listener should I use?

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, the text field is for the date and I have a calendar which can be used to select the date and populate the text field. Now whenever there is a change in the text field I want to trigger an action. So which kind of listener should I use?

Share Improve this question asked Aug 9, 2011 at 7:39 rajan sthapitrajan sthapit 4,37410 gold badges44 silver badges67 bronze badges 1
  • Are you using some library to generate the Calendar? If so, that library might provide hooks to listen for changes. I don't believe there is any JavaScript event that will fire when a property is changed programmatically. – OverZealous Commented Aug 9, 2011 at 8:06
Add a ment  | 

2 Answers 2

Reset to default 5

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.

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:

function watchField(fieldId, callback) {
    var previousVal = null;

    return setInterval(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. ;-)

发布评论

评论列表(0)

  1. 暂无评论