admin管理员组文章数量:1387454
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
2 Answers
Reset to default 5Depending 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. ;-)
本文标签: javascriptAdding text change listener to a text boxStack Overflow
版权声明:本文标题:javascript - Adding text change listener to a text box - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744546305a2611914.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论