Reputation: 2904
How can I get the id
attribute of a dynamically generated element when you don't know it's id
? I am wanting to setup some eventListener
s for about 2000 Checkbox's on a page.
I know I could call a function from within the element:
<input type="checkbox" id="{databaseResult.Value}" onclick="someFunction(this)" />
But I'm not allowed to use JavaScript, or references to it in my HTML. Pure JavaScript (or a language that compiles to it) is my only option.
The code I already have for some elements where I do know the id
, is:
var tb = <HTMLInputElement>document.getElementById("tbox");
if(tb.addEventListener("", function (e) {
sayHello(tb.value);
}, false));
Upvotes: 1
Views: 3105
Reputation: 147413
Put a single listener on an ancestor element, say the body, and listen for events on that, e.g.:
<body onclick="handleClick(event);" ...>
and the function is:
function handleClick(evt) {
var el = evt.target || evt.srcElement;
if (el && el.type == 'checkbox') {
alert(el.id);
}
}
Of course you can add the listener dynamically, I've used inline for convenience.
To attach the listener dynamically, use an addEvent
function to cope with IE and W3C event models:
function addEvent(el, evt, fn) {
// W3C event model
if (el.addEventListener) {
el.addEventListener(evt, fn, false);
// IE event model
// Set this and pass event as first parameter
} else if (el.attachEvent) {
el.attachEvent('on' + evt, (function(el, fn) {
return function() {fn.call(el, window.event);};
})(el, fn)
);
}
// Prevent circular reference
el = null;
}
And call it as:
window.onload = function() {
addEvent(document.body, 'click', handleClick);
}
Upvotes: 2