Adding event listeners to multiple elements

Christian Lundahl picture Christian Lundahl · Dec 17, 2012 · Viewed 38.6k times · Source

I've been struggling with this for a good couple of hours now.

I want to add an event listener to all <select>s on a page and I've got this piece of code so far:

onload = function(e) {
    sels = document.getElementsByTagName('select');
    for(i=0; i<sels.length; i++) {
        sels[i].addEventListener('change', alert('test!'), false);
    }
}

This only triggers the alert when the page is loaded and not when I change the value in any of my <select>s.

Can I get a nudge in the right direction, please? :-)

Answer

antyrat picture antyrat · Dec 17, 2012

You need to have there anonymous function for that as you invoke alert() function immediately in your example:

 ... .addEventListener('change', function() { alert('test!')}, false ...

For now according to your code addEventListener tries to add result of undefined (return of alert() function).

Or you can just pass function handler for that:

function alertMe() {
    alert( 'test!' );
}
...

... .addEventListener('change', alertMe, false ...

Note: that by making somefunction(arg[, arg...]) call you reference not to function, but to what function returns.