user2405469
user2405469

Reputation: 2003

event listener in javascript not firing except for when the page is loaded

I am trying this:

//this represents all of the select tags on the page
var select = document.getElementsByTagName("select");

//Listener for when the option changes
select.addEventListener("change", hi(), false);

function hi() {
  alert("hi");
}
<select>
  <option>one</option>
  <option>two</option>
</select>

but the event listener does not seem to be working, in jsfiddle it works when the page loads, but not when I change the option...

Upvotes: 4

Views: 1150

Answers (1)

johnnycardy
johnnycardy

Reputation: 3046

Remove the brackets from the function name:

select.addEventListener("change", hi, false);

You're calling the function and attaching its result, instead of attaching the function itself.

Edit: Also, as Teemu points out, you're trying to attach to a collection instead of an individual select item. Try var select = document.getElementsByTagName("select")[0]; - or better still, use getElementById.

Upvotes: 6

Related Questions