I’ve been messing around with event listeners, but can’t figure out the correct syntax for doing this, so I thought I’d see if anyone could lend a hand.
I have a page with a large number of input fields - including radio buttons, checkboxes, textareas and dropdowns. I need to detect when the user’s changed any of these fields. In the past, I’ve manually added onchange handlers to each field, which seemed a good idea at the time, but now strikes me as rather labour intensive - to say the least.
I’d like to simply define one onchange handler for the HTMLInputElement, one for the HTMLSelectElement, etc. etc. so that it would simply toggle a “isChanged” global variable. Anyone have any idea about how to pull this off?
There are a few ways you could go about this, (GPH’s way looks nice), but I prefer to do things like this, so that I can mix and match between functions and give me more flexibility.
function addEvent(obj, evType, fn) {
if (obj.addEventListener) {
obj.addEventListener(evType, fn, false);
return true;
} else if (obj.attachEvent) {
var r = obj.attachEvent("on"+evType, fn);
return r;
} else {
return false;
}
}
function isChanged (el) {
alert(el.value);
}
function inputHandler() {
if(!document.getElementsByTagName) return;
var inputs, selects, textareas, i;
inputs = document.getElementsByTagName('input');
for(i=0;i<inputs.length;i++) {
if(!(/submit/).test(inputs[i].getAttribute("type"))) {
inputs[i].onchange = function(){isChanged(this)};
}
}
selects = document.getElementsByTagName('select');
for(i=0;i<selects.length;i++) {
selects[i].onchange = function(){isChanged(this)};
}
}
addEvent(window, 'load', inputHandler);