Home > Net >  Why I can't add "keydown" event on td >p element?
Why I can't add "keydown" event on td >p element?

Time:12-23

I want to trigger some action when user press a key inside a p tag inside a td element, here is the HTML of a "td" on my table.

The problem is that when I add the keydown event to every paragraph element I don't see any response. Here is how I did it.

document.querySelectorAll('tr').forEach((row) => {
  if (row.rowIndex > 0) {
    row.querySelectorAll('td').forEach((cell) => {
      cell.contentEditable = true;
      cell.querySelectorAll('p').forEach((prg) => {
        prg.addEventListener('keydown', () => {
          console.log('test');
        });
      });
    });
  }
});
<table>
  <tr></tr>
  <tr>
    <td data-property="phone" contenteditable="true">
      <p data-property="phone" >34567890</p>
      <p data-property="phone" >5511525298ss</p>
      <p data-property="phone" >5511525298</p>
    </td>
  </tr>
</table>

I had some other "keydown" events on the "td" elements but when I removed them it still not working.

When I use the "click" event instead "keydown" I obtain the response that I expect.

I read here https://www.w3schools.com/Jsref/event_onkeydown.asp that keydown event is supported in "p" and table elements.

I need to obtain the p in which the text editing is happening for update server info so add the event on the table cell is not working for me.

I really appreciate any help with this, links to read or suggestions.

CodePudding user response:

If you shift the contentEditable onto the paragraph tags it will work.

document.querySelectorAll('tr:not(:first-child) td p').forEach((prg) => {
  prg.setAttribute('contentEditable', true);

  prg.addEventListener('keydown', () => {
    console.log('test');
  });
});
<table>
  <tr>
    <td colspan='10'>First row</td>
  </tr>
  <tr>
    <td data-property="phone">
      <p data-property="phone" >34567890</p>
      <p data-property="phone" >5511525298ss</p>
      <p data-property="phone" >5511525298</p>
    </td>
  </tr>
</table>

  • Related