JavaScript event handler arguments

I have the following JavaScript code:

var ans_el = document.createElement( 'input' ); ans_el.setAttribute( 'id', unique_int_value ); ans_el.setAttribute( 'type', 'radio' ); ans_el.setAttribute( 'name', 'group' ); ans_el.setAttribute( 'value', 'myValue' ); ans_el.onclick = myFunction( this.id, this.value ); // Add ans_el to DOM. function myFunction( index, value ) { // do something } 

This, of course, does not work properly. At least not in Firefox 3.6. It happens that the onclick event is fired when the element is created, and the arguments passed to myFunction are zero. After adding an item to the DOM, the onclick event does not fire when a radio button is selected.

I would be grateful if someone finds out what is happening here, and / or how to add event handlers dynamically.

+6
javascript javascript-events
source share
1 answer

You need to give a link to the onclick function; you are currently executing a function and assigning this result to the onclick handler. This is closer to what you want:

 ans_el.onclick = function(e) { myFunction(ans_el.id, ans_el.value); }; 

UPDATED: decided to use event.target for a clearer example, since Andir raised it.

 ans_el.onclick = function(e) { myFunction(e.target.id, e.target.value); }; 
+11
source share

All Articles