I have a table that is added dynamically. The keypress
event is not working on tr
and td
. The event is not fired. But it fires if I use the table
or the class of table like '.loaded-table'
. Here is my code.
$(document).on("keypress", '.loaded-table tr', function (event) {
var key = event.which;
if(key === 13){
event.preventDefault();
alert();
}
});
And here is the HTML
code of dynamically loaded table.
<table contenteditable="true" class="table table-bordered loaded-table">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>father_name</th>
<th>dob</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>John</td>
<td>Robert</td>
<td>12-04-1992</td>
</tr>
</tbody>
</table>
I don't think that I have a problem in selecting the element for the event. You may know better. Thanks
You need to remove contenteditable="true"
from table tag and add it to either tr
or td
in order to allow keypress event to fire. In this example I have added contenteditable="true"
to all tds for which I want to fire the keypress event.
$('body').on("keypress", '.loaded-table tr td', function(e) { var keyC = e.keyCode; if (keyC == 32) { alert('Enter pressed'); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <table class="table table-bordered loaded-table"> <thead> <tr> <th>id</th> <th>name</th> <th>father_name</th> <th>dob</th> </tr> </thead> <tbody> <tr> <td contenteditable="true">1</td> <td contenteditable="true">John</td> <td contenteditable="true">Robert</td> <td contenteditable="true">12-04-1992</td> </tr> </tbody> </table> </body>
OR simply use <input>
element
<tr><td><input type="text"></td>....</tr>
This works too. Notice the ,
after .loaded-table
.
$(document).on("keypress", '.loaded-table, tr', function(e) {
var keyC = e.keyCode;
if (keyC == 32) {
alert('Enter pressed');
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.