5

I created a html table and set the td elements to contenteditable = true. If I click somewhere else on the page I "end" the editing of the content which means the cell isn't highlighted anymore and typing characters doesn't add them to the cell.

I want to achieve this on pressing the return key. I already have a key listener to prevent the user from inserting line breaks when pressing the return key:

document.addEventListener('keydown', function (event) {
    if (event.key === 'Enter') {
        event.preventDefault();
        var value = event.target.innerHTML;
        // do something with the value
    }
});

How do I "end" editing (something like jump out of the cell) on pressing the return key?

The td elements all look like this:

<td class="memory-cell" id="memory-cell-45" data-cell-number="45" width="100" contenteditable="true">0</td>

UPDATE: I ended up on setting contenteditable = true on click and removing the contenteditable attribute on return key press.

1 Answer 1

3

Bind the onkeydown to document or preferably the editable element, and then remove the contenteditable property on keydown, if it's the Enter key that is pressed.

You can also bind to document.querySelector(".memory-cell").onkeydown if youwant to disable it outside div.

document.onkeydown = function(event) {
  if (event.key === 'Enter') {
    event.preventDefault();
    document.querySelector(".memory-cell").removeAttribute('contenteditable');
  }
}

function enableEditing(element){
  //Adds the content editable property to passed element
  element.setAttribute('contenteditable', true)
  //Focuses the element
  element.focus()
}
<table border="1">
  <tr>
    <td class="memory-cell" onclick="enableEditing(this)" id="memory-cell-45" data-cell-number="45" width="100" contenteditable>0</td>
  </tr>
</table>

PS: The additional table element in below snippet was added for reference only

6
  • But I want the user to be able to edit the content again. Removing is not an option. Apr 9, 2021 at 8:51
  • 1
    Add it again using .setAttribute('contenteditable', true) whenever you need to be editable
    – Ajith Gopi
    Apr 9, 2021 at 8:52
  • @elementzero23 add another event “onclick” on the same element and add the contenteditable attribute then. Also, make a change in your CSS for the td class cursor: pointer so that your td elements always look editable.
    – Ajay Gupta
    Apr 9, 2021 at 8:55
  • I have modified the answer so that editing is re-enabled on double click. Please add to the question too, so future spectators doesn't get confused about why it's there!
    – Ajith Gopi
    Apr 9, 2021 at 8:58
  • 1
    OK, I used focus for this. Apr 9, 2021 at 9:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.