themisterunknown
themisterunknown

Reputation: 771

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

Upvotes: 10

Views: 16879

Answers (4)

Seimen
Seimen

Reputation: 7250

You should have a reference to the element in the event: event.target.

Upvotes: 2

Sebastien C.
Sebastien C.

Reputation: 4833

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

Upvotes: 13

matewka
matewka

Reputation: 10148

The this keyword is already in the function

<script>
function chmod(e) {
    var elem = this;
}
</script>

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

Upvotes: 0

sroes
sroes

Reputation: 15053

I'd do the following:

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

Then your js:

function chmod(e) {
    var element = e.target;
    ...
}

Upvotes: 2

Related Questions