Search code examples
javascripteventsargumentsonkeyup

JavaScript; How to add arguments to events?


I have a website that uses pure JavaScript (no JQuery) and I would like to trap events on a textbox. The textbox is in a table, and there may be multiple tables (with their own ID's) on the page. The textbox is dynamically created by the Javascript and added to the table after the HTML table is delivered to the browser.

I am trying to trap the onkeyup event, and know the table that contains the textbox that triggered the event.

The function that gets attached to the onkeyup event gets called with an argument, the event itself, that gives info about the key that was just pressed. That's great, I can get that, and I know the key, all good.

textbox.onkeyup = my.namespace.textboxAge;

my.namespace.textboxAge = function (event) { 
    console.log("I got the event:" + event.ToString()); };

What I need to do is attach additional information to the function call, so that I get the original event, plus the table or table ID.

I have thought about a closure to trap in the table reference when I attach my handler to the onkeyup event, something like...

var table = document.getElementByID("table5");
textbox.onkeyup = function (event,table) { 
    console.log("I got event:" + event.ToString() + " on table " + table.id); }

But this does not work, event is not set when the closure function is attached, so it remains null when onkeyup fires.

I have worked around this for now, but I am confused as to how to add information to events and would like to know if it is possible, and how to do it.


Solution

  • Remove the argument from your event function. In your code, the table variable gets overwritten in the event function call. If you omit it from the parameter list, you have the original value:

    var table = document.getElementByID("table5");
    textbox.onkeyup = function (event) { 
        console.log("I got event:" + event.ToString() + " on table " + table.id); }