Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 820
Bruce Avatar asked Jul 14 '10 18:07

Bruce


People also ask

Can you pass arguments to event handler?

If you want to pass a parameter to the click event handler you need to make use of the arrow function or bind the function. If you pass the argument directly the onClick function would be called automatically even before pressing the button.

What arguments does the addEventListener method take?

The addEventListener() is an inbuilt function in JavaScript which takes the event to listen for, and a second argument to be called whenever the described event gets fired. Any number of event handlers can be added to a single element without overwriting existing event handlers.

How do you pass an arguments callback function in event listener?

Here is the code: var someVar = some_other_function(); someObj. addEventListener("click", function(){ some_function(someVar); }, false);

What are event arguments?

The second, called the event argument, contains information specific to the event, if any. For most events, the event argument is of type EventArgs, which does not expose any properties. So, the general prototype for an event in Visual Basic is: Private Sub EventName (ByVal sender As Object, _ ByVal e As EventArgs)


1 Answers

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);
};
like image 80
sunetos Avatar answered Sep 22 '22 15:09

sunetos