An SO User
An SO User

Reputation: 24998

Why won't the onChange event, of the select, fire?

function updateText(){
    alert(fontsize.options[fontsize.selectedIndex].value);
}

var fontsize = document.getElementById("fontsize");
fontsize.addEventListener('onChange','updateText',false);  

This is my JavaScript to handle the selection of font sizes on my webpage. However, nothing happens when I select different values in the dropdown.

There are no errors in the console log, either.

So, my questions are:
1. Why won't it work ?
2. Why is using event delegation model recommended over <select onchange="someMethod()">

Upvotes: 0

Views: 93

Answers (2)

Felix Kling
Felix Kling

Reputation: 816422

Two problems:

  1. The event is called change, not onchange. onchange is the name of an HTML attribute and a DOM property.

  2. You have to pass a function to addEventListener, not a string.

So

fontsize.addEventListener('change', updateText, false);

should work.

It seems you are mixing inlineor traditional event handlers with advanced event handlers.

Equivalent inline event handler:

<select id="fontsize" onchange="updateText()">

or (don't do that):

fontsize.setAttribute('onchange', 'updateText()');

Unless you are only prototyping something, using inline event handlers is generally not a good idea, see below.

Equivalent traditional event handler:

fontsize.onchange = updateText;

Why is using event delegation model recommended over <select onchange="someMethod()">

This has nothing to do with event delegation. Event delegation is a concept independent from the way the event handlers are bound. For a practical reason not to use inline event handlers, see my answer here onclick="" vs event handler.

I also recommend to read the articles on quirksmode.org which in my opinion explain everything you need to know about event handlers.

Upvotes: 4

The Alpha
The Alpha

Reputation: 146191

Because it should be

fontsize.addEventListener('change', updateText, false);

Not onChange.

Upvotes: 0

Related Questions