Jump to content

how to catch event while passing other parameters?

Recommended Posts

I want to capture keypress event while passing other value in function. I've already and still googling but still not found the answer.Here is the coding :

function inputkeyup(i){if (event.keyCode!==13){// do something like thisalert(i.value)};};<input name="myipt" type="text" id="myipt" size="15" maxlength="12" onKeyUp="inputkeyup(this)"><input name="myipt2" type="text" id="myipt2" size="15" maxlength="12" onKeyUp="inputkeyup(this)">

Latest Firefox console tell "ReferenceError: event is not defined" and the code is not functioning :(

How to make it working? :crazy:

No jQuery please because I will learn nothing.


Thanks for any help.

Edited by Fiq

Share this post

Link to post
Share on other sites

The global event object is only defined in IE. There's a good description about event handling here:http://www.quirksmode.org/js/introevents.htmlThe link to the next section about events is in the middle of the page, if you can't find it this is the next article:http://www.quirksmode.org/js/events_events.html

Share this post

Link to post
Share on other sites

You mean like this?

function inputkeyup(event){    if (event.keyCode!==13){        // do something like this        alert(this.value)    };};    document.getElementById("myipt").onkeyup   =    document.getElementById("myipt2").onkeyup  = inputkeyup;
<input name="myipt" type="text" id="myipt" size="15" maxlength="12"><input name="myipt2" type="text" id="myipt2" size="15" maxlength="12">

When triggering an event, Javascript implicitly passes the "event" object to the function (on most browsers) if you don't directly pass in an actual parameter when the function accepts one. Notice that when I have inputkepup called I didn't pass any variable, Javascript sees that it can take a variable and will automatically pass in the event object for me. You just simply needed to put "event" inside the parameters.


I also never need to pass in the "this" reference, the function will already know which element called it. This is because Javascript automatically binds the "this" reference to the element that is triggering the event for you. So you need not worry about passing in the this.

Share this post

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.


  • Create New...