1

I have a javascript event handler like this:

for (i = 0; i < x; i++){
 var table = tableList[i];
 var tableID = table.getAttribute('id');

 var selector = table.querySelectorAll('input')[0];
 selector.on('focusout', function(){
    alert(tableID);
 }):
}

The tableID alert is always the ID of the last table in the tableList, regardless of which table I am using.

Any ideas?

daniely
  • 7,313
  • 5
  • 29
  • 46
  • 2
    possible duplicate of [Javascript closure inside loops - simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Ian Jun 12 '13 at 20:02
  • Do you have the same `id` applied to multiple elements? – ayyp Jun 12 '13 at 20:02
  • Why `table.querySelectorAll("input")[0]` instead of `table.querySelector("input")`? Also, `selector` seems like an odd variable name for referencing an element. And `table.getAttribute("id")` can be `table.id;`. –  Jun 12 '13 at 20:15

1 Answers1

1

You may attach the tableID as a data object to your event handler. Try the following.

selector.on('focusout', { tableID: tableID }, function(e) {
    alert(e.data.tableID);
}):

Per the jQuery documentation.

//data
//Type: Anything
//Data to be passed to the handler in event.data when an event is triggered.
Brad M
  • 7,857
  • 1
  • 23
  • 40