Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Pass event AND element reference

I want an input field which calls a javascript function, if a key is pressed. But I'm not able to pass the event as well as an element reference. I can either pass the event:

<input type="text" name="chmod" value="644" onkeypress="chmod(e)">

or pass the element reference:

<input type="text" name="chmod" value="644" onkeypress="chmod(this)">

If I try to pass both there occurs an error:

<input type="text" name="chmod" value="644" onkeypress="chmod(e, this)">

Uncaught ReferenceError: e is not defined

Is there any way to pass both, the event and a reference to the element?

Cheers, Marco

like image 681
themisterunknown Avatar asked Nov 08 '13 11:11

themisterunknown


People also ask

How do you pass an event in JavaScript?

To pass an event object to a function in JavaScript, we can use the addEventListener method. const onClick = (ev) => { ev. preventDefault(); console.

How do you pass parameters in an event?

Passing the event object of react as the second argument. 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.

How do I pass onClick event?

To pass an event and parameter onClick in React:Pass an inline function to the onClick prop of the element. The function should take the event object and call handleClick . Pass the event and parameter to handleClick .

What is e in Eventlistener in JS?

The parameter e that you are asking about is an Event object, and it represents the event being fired which caused your function to be executed. It doesnt really have to be e , you can name it anything you want just like all other function parameters.


1 Answers

I'd do the following:

<input type="text" name="chmod" value="644" onkeypress="chmod">

Then your js:

function chmod(e) {
    var element = e.target;
    ...
}
like image 193
sroes Avatar answered Oct 15 '22 20:10

sroes