Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keypress event on dynamically added element is not working

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

like image 331
Maseed Avatar asked Jun 17 '17 16:06

Maseed


2 Answers

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>
like image 159
Raj Avatar answered Oct 02 '22 16:10

Raj


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');
    }
});
like image 25
user3310115 Avatar answered Oct 02 '22 17:10

user3310115