Reputation: 5158
I have a few readonly textfields and a datepicker written in plain old javascript. The problem is I need to detect when the text is being set, but since that same js is used everywhere across the site, I can't really put code(like something.trigger('change')
) inside the js file. Is there any other way to detect the change without modifying the calendar js?
Upvotes: 2
Views: 96
Reputation: 207511
Well onchange does not fire if the value is changed with JavaScript which stinks in some cases.
There were mutation events, but they were deprecated and the future there will be Mutation Observers, but they will not be fully supported for a long time. So what can you do in the mean time?
You can use a timer to check the element.
function addValueListener(elemId, callback) {
var elem = document.getElementById(elemId);
var lastValue = elem.value;
window.setInterval( function() {
var value = elem.value;
if (value !== lastValue) {
callback();
lastValue = value;
}
},10);
}
written as jQuery:
function addValueListener(elemId, callback) {
var elem = $(elemId);
var lastValue = elem.val();
window.setInterval( function() {
var value = elem.val();
if (value !== lastValue) {
callback();
lastValue = value;
}
},10);
}
Running Example: jsFiddle
Upvotes: 2