attaching event handlers to tags with javascript

Y

yawnmoth

Say I had <select id="something" name="something"
onchange="demo(this.value)"> but didn't want to define the onchange
event handler in the select tag, itself. ie. I wanted to attach it,
latter, by doing something like...

document.getElementById('something').attachEvent('onchange',demo);

or this:

document.getElementById('something').onchange = demo;

How would I go about passing parameters to demo as I do in the select
tag? Is there a way I could reference this.value in demo without
having to pass it as a parameter to demo?
 
R

RobG

yawnmoth said:
Say I had <select id="something" name="something"
onchange="demo(this.value)"> but didn't want to define the onchange
event handler in the select tag, itself. ie. I wanted to attach it,
latter, by doing something like...

document.getElementById('something').attachEvent('onchange',demo);

Don't forget to include a fork for addEventListener. Try this post by
Alexis Nikichine titled "IE's Dummy attachEvent?":

<URL:
http://groups.google.com.au/group/c...event+pass+parameters&rnum=4#4c56d9d7b56f1efe
Copied below:

function makeEventFunc( param1, param2 )
{
return function()
{
alert( "param1 = " + param1 + "\nparam2 = " + param2 );
}

}

objElement. attachEvent ( "onclick", makeEventFunc( param1, param2 ) );

That way, makeEventFun will return you a closure, i.e. a function who
"remembers" what values were bound to param1 and param2. This
"function" can then be passed to attachEvent .

Hope this helps,

Alexis


or this:

document.getElementById('something').onchange = demo;

var x = document.getElementById('something');
x.onchange = function() {
demo(parm1, parm2);
}


'x' used for posting sans auto-wrapping.
How would I go about passing parameters to demo as I do in the select
tag? Is there a way I could reference this.value in demo without
having to pass it as a parameter to demo?

If you have:

document.getElementById('something').onchange = demo;


Then in demo() 'this' will refer to the element with id 'something'.


e.g.


window.onload = function() {
document.getElementById('something').onchange = demo;
}


function demo(){
alert(this.id); // shows 'something'
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,007
Latest member
obedient dusk

Latest Threads

Top