Search code examples
javascripthtmlhtml-tableelementonkeypress

Preventing html ENTER event without disabling keypress


I'm building a spreadsheet site using <tr contenteditable="true"> for cells.

I've implemented an onkeyup function whereby pressing enter when focused on a cell shifts focus to the next cell directly below, but the problem is that pressing enter by default also adds a line break with contenteditable elements, resulting in an empty line being created before moving on the next cell.

enter image description here

Both fire at the same time, so I don't have a chance to cancel the keypress without also breaking my function. All of the solutions I've found involve completely disabling the enter key when focused on the element, but that won't work here since my function relies on being able to press enter while focused on the element.

All I need is for the tr to not insert a <br> on enter, I do not need to disable my enter key.


Solution

  • Adding e.preventDefault() on enter events solved the issue. Make sure you only put it on the enter key and not for all keypresses otherwise you will disable text input for the cells preventing you from being able to edit them, and make sure to use onkeypress/onkeydown and not onkeyup.

    Big thanks to @Robin Clower and @Zac in the comments.