-1

I am implementing the view behavior using jQuery. I can input directly to the table td. I want to give an event when inputting to this td.

But the event is not recognized, what should I do?

Here is the code:

<div class="a">
   <table class="tb">
      <tr>
         <td></td>
      </tr>
   </table>
</div>
<script type="text/javascript">
   $(".a table tr td").on('keypress', function(event){
      console.log(event);
   });
</script>

It is an event required only on the page, so it is difficult to modify the common jQuery code that draws and enters the table.

Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
limsrs
  • 121
  • 1
  • 3
  • 10

2 Answers2

2

The below code works, so if it doesn't work in your case, that probably means that the <input> field is not yet added by your other "common" code, at the time you add the keypress listener.

So the solution should be to first add the <input> fields, and after that you execute your key handler code.

<div class="a">
  <table class="tb">
    <tr>
      <td><input type="text"></td>
    </tr>
  </table>
</div>

Execute this AFTER the input fields have been added

$(".a table tr td").on("keypress", function (event) {
  console.log(event.key);
});

Working example here: https://jsfiddle.net/081cL2xu/

Kokodoko
  • 26,167
  • 33
  • 120
  • 197
2

Based on this:

A keypress event handler can be attached to any element, but the event is only sent to the element that has the focus

So you need to have focusable element, see this to know what are the focusable element: Which HTML elements can receive focus?

If I have textbox in td everything going to be fine:

$(".a table tr td").on('keypress', function (event) {
  console.log(event.key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div class="a">
        <table class="tb">
            <tr>
                <td><input /></td>
            </tr>
        </table>
    </div>
Alireza Ahmadi
  • 8,579
  • 5
  • 15
  • 42
  • @limsrs Yes also `keypress` need focusable element – Alireza Ahmadi Aug 16 '21 at 09:24
  • I made it possible to receive input in td using script code. I do not know the details because I did not develop the part, but the conclusion is that the grammar you pointed out is because I made a typo while writing it using a smartphone, and it is written normally in the place where it is actually developed. Also, it is written without input in td. – limsrs Aug 16 '21 at 09:25
  • @limsrs So now your problem has been solved? Is there any question? – Alireza Ahmadi Aug 16 '21 at 09:27
  • I think I'll have to try adding elements after talking with my supervisor tomorrow. Thanks. – limsrs Aug 16 '21 at 09:29