Arnold Arnold - 7 months ago 44
HTML Question

How to determine in which table row <tr> the keyup event is triggered?

I have a long table (10,000 rows, 10 columns) that can be edited on screen. After editing, the changes can be saved. Since I do not want to re-save the entire table I want to keep track of the rows where changes have been made. Each row-tag has a unique id as well as the table-tag. But using .keyup only functions with $('table') and not with $('tr') or $('td') and always returns the is of the table-tag. Here's a short example of my html-code:

<table id="table1" contenteditable="true">
<tr id="tr1"><td>Cell 11</td><td>Cell 12</td><td>Cell 13</td></tr>
<tr id="tr2"><td>Cell 21</td><td>Cell 22</td><td>Cell 23</td></tr>
</table>


And in jQuery I've tried several things like:

$(document).ready(function() {
$('table').keyup(function(e) {
alert($(this).attr('id'));
});
});


This always results in 'table1'. How can I get 'tr1', 'tr2', etc.?

Answer

Use e.target to see the element that originated the event and then use .closest("tr") to go up the parent hierarchy from there to get the row.

$(document).ready(function() {
  $('table').keyup(function(e) {
    console.log($(e.target).closest("tr").attr("id"));
  });
});

FYI, you won't be able to get any key events in your table until you put something in the table that can accept focus (like an <input> tag).

Working demo: https://jsfiddle.net/jfriend00/1j7vkfma/

Comments