JS: dynamic onclick event handler creation troubles...

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
mechamecha
Forum Commoner
Posts: 32
Joined: Thu May 31, 2007 8:49 pm

JS: dynamic onclick event handler creation troubles...

Post by mechamecha »

feyd | Please use

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]


Hey All,
I'm having problems creating onclick event handlers by editing the dom in javascript.

Sample pseudo code:

[syntax="html"]
//DOM:
<div id='containerDiv>
  <input type='button' />
  <input type='button' />
  <input type='button' />
</div>

//js code:

var l_div = $('containerDiv');

for( var i=0; i<3; i++ )
{
  var l_inputButton = l_div.getChildElements()[i];
  var l_arg = "arg_" + i;
  l_inputButton.onclick = function() { some_js_function( l_arg ); };
}
What I'm trying to do here is iterate through all buttons in the dom and add an event handler w/ a unique argument. The argument is built based on the index of the button.

The problem is javascript stores a reference to that argument instead of a value. So all onclick event handlers have their arguments pointing to the last argument generated...in the case of this example, 'arg_2'.

Anyone know of a solution to this problem? I'm looking for the simplest "cross bowser support" solution. What is the standard convention for dynamically creating event handlers?

One solution I have thought of is to assign the index of the button to it's id. Then in the event handler's function argument is just "this.id". Is this a hack? And what happens if I want multiple arguments? Do i begin assigning these arguments to the buttons' other attributes (ie. name, class, etc...). This is looking more and more like a hack.

Thanks.


feyd | Please use[/syntax]

Code: Select all

,

Code: Select all

and [syntax="..."] tags where appropriate when posting code. Your post has been edited to reflect how we'd like it posted. Please read:  [url=http://forums.devnetwork.net/viewtopic.php?t=21171]Posting Code in the Forums[/url] to learn how to do it too.[/color]
User avatar
VladSun
DevNet Master
Posts: 4313
Joined: Wed Jun 27, 2007 9:44 am
Location: Sofia, Bulgaria

Post by VladSun »

You can create object Function like this:

Code: Select all

var s = "Hello, world!"
element.onclick = new Function("alert(' "+ s + " ')");
There are 10 types of people in this world, those who understand binary and those who don't
mechamecha
Forum Commoner
Posts: 32
Joined: Thu May 31, 2007 8:49 pm

Post by mechamecha »

Awesome!
Thanks so much VladSun! Your solution works perfectly. Tested on Firefox, IE 6, Opera, and Safari.
Post Reply