Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
158
rated 0 times [  163] [ 5]  / answers: 1 / hits: 23224  / 14 Years ago, wed, july 14, 2010, 12:00:00

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 as expected. At least not in Firefox 3.6. What happens is the onclick event is fired when the element is created and the arguments passed to myFunction are null. After the element is added to the DOM, the onclick event does not fire when the radio button is select.


I'd be grateful if anyone has some insight into what's happening here, and/or how dynamically adding event handlers can be accomplished.


More From » dom-events

 Answers
5

You need to give a reference to a function for onclick; you are currently executing the function and assigning that 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 brought it up.



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

[#96228] Tuesday, July 13, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
americar

Total Points: 631
Total Questions: 107
Total Answers: 103

Location: Luxembourg
Member since Tue, Jan 25, 2022
2 Years ago
;