user2103677
user2103677

Reputation: 33

Creating a HTML DOM select element in Javascript and having an onchange event

I am creating HTML DOM elements using Javascript (yes, I know it's nasty).
I can get the select element created but I cannot add an onchange property.

Example:

var sel = document.createElement('select');
sel.id = 'someID';
sel.title = 'Some title';
sel.style.fontWeight = 'bold';
sel.size = 1;

Once I have added the options and have done a
document.getElementById('someOtherID').appendChild(sel);
I get my select element.

What I want to do is, at A above, add:
sel.onChange = 'someJavascriptFunction()';
but it doesn't like it.

Should I be thinking outside of the square? Which one?

Upvotes: 3

Views: 7368

Answers (4)

OsamaBinLogin
OsamaBinLogin

Reputation: 647

An easier way to do the whole thing is: somewhere already in your page:

<div id=someContainer></div>

then in your javascript do this:

document.getElementById('someContainer').innerHTML = "<select id=someId title='some title' size=1 style='font-weight: bold' onchange='someJavascriptFunction()' >";

or more slowly:

var html = "<select id=someId title='some title' size=1 style='font-weight: bold' onchange='someJavascriptFunction()' >";

var someContainer = document.getElementById('someContainer');

someContainer.innerHTML = html;

The document.getElementById() is so common, you might have a library like jquery or prototype that does that more easily like $('someContainer'), or else define it for yourself (var $ = document.getElementById;).

innerHTML is a pseudo-variable on every dom element that returns, or sets, all the html INSIDE the element you do it on. You can pass it arbitrarily long HTML, the whole page I guess if you want. and you can write a crafty program to build the html text, they even have templating systems like hogan (google it).

Upvotes: 0

jthomas
jthomas

Reputation: 858

If there's a chance you'll be binding multiple functions to that event, you will want to use this slightly more lengthy method.

if (sel.addEventListener) {
    sel.addEventListener('change', changeFunction, false);
} else if (sel.attachEvent) {
    sel.attachEvent('onchange', changeFunction);
} else {
    sel.onchange = changeFunction;
}

Upvotes: 0

the system
the system

Reputation: 9336

The event name should be lowercase, and you need to assign a function instead of a string.

sel.onchange = someJavascriptFunction;

If there's more work to do, you can assign an anonymous function.

              //  v----assign this function
sel.onchange = function() {
    // do some work
    someJavascriptFunction();  // invoke this function
};

Upvotes: 3

Andrew Eisenberg
Andrew Eisenberg

Reputation: 28757

You should be doing something like this:

sel.onChange = someJavascriptFunction;

(notice that there are no parens after someJavascriptFunction. This means you are attaching the function, not the invocation of the function.

Upvotes: 0

Related Questions