10

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

1
  • Do you have access to use a JavaScript library like jQuery? This is a good example (cross browser pain) where being able to use a library lets you define your event handlers separately and bind them to the field(s) you want to use them on... overcoming the limitations of IE's legacy global event object, and manually passing the event in other browsers via inline event handlers. jQuery's keypress event handler: api.jquery.com/keypress for example. Commented Nov 8, 2013 at 11:19

4 Answers 4

13
<input type="text" name="chmod" value="644" onkeypress="chmod(event, this)">
Sign up to request clarification or add additional context in comments.

Comments

2

I'd do the following:

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

Then your js:

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

1 Comment

👍 I am looking for this solution exactly
2

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

1 Comment

Thank you. That is also a solution.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.