Search code examples
jquerybootstrap-table

Problems with JQuery keypress in Bootstrap-Table: data-toggle="table"


I'm using Bootstrap Table https://bootstrap-table.com/ I'm trying to validate inputs in my table, so I'm using JQuery keypress function. But when I try to use keypress on inputs inside the table it doesn't work. I tried many methods, but the only way was deleting: [data-toggle="table"] from my table, then keypress works again. Do you know what can I do to use the keypress function when I'm using bootstrap table? Here is my code: (I'm using: https://bootstrap-table.com/ and JQuery)

<table id="table_1" data-toggle="table" data-pagination="true">
    <thead>
         <tr>
            <th>
                ID
            </th>
            <th>
                Name
            </th>
         </tr>
    </thead>
    <tbody>
         <tr>
            <td>
                <input id="input_1" type="text" />
            </td>
            <td>
                <input id="input_2" type="text" />
            </td>
         </tr>
    </tbody>
</table>


<script>

$('#input_1').keypress(function() {
    alert('It works!');
});

$('#input_2').keypress(function() {
    alert('It works!');
});

</script>

Solution

  • You might be having an issue with the <table> being re-rendered by the Bootstrap-Table plugin.

    Thus your events are getting lost.

    To avoid this (in case this is the issue) you should use the following code:

    $('#table_1).on("keypress", "#input_1", function(e) {
        alert('It works!');
    });
    

    And do the same with the other one. You can swap #table_1 with something like body or document too and it might work.