Change the value of a <textarea> and allow the user to undo
Asked Answered
B

1

6

In the past, when you set the value of a textarea using javascript, Firefox allowed the user to undo this change (by pressing ctrl+Z, for example). However, this no longer works, and there doesn't appear to be any decent alternatives.

I've tried using document.execCommand to modify the textarea, but this requires you to select the text that you want to modify, and it doesn't appear to be possible to automatically select text in a textarea.

I've also heard about document.createEvent("TextEvent") but I can't find much information about this. It appears that you can only insert text at the cursor, and I need to delete text as well.

Creating my own undo/redo system and capturing ctrl+Z/Y presses is not an acceptable solution.

Similar questions have already been asked here, but they involve only inserting text at the cursor, not changing the value of the textarea entirely.

Benedikta answered 11/8, 2018 at 2:41 Comment(4)
Does this answer your question? Is it possible to edit a text input with javascript and add to the Undo stack?Humanity
@Humanity No, it doesn’t the answer the question, as it uses a deprecated API.Internee
document.execCommand is only deprecated on paper, there's no alternative API for this, so "deprecation" is meaningless.Humanity
"execCommand() is now obsolete, what's the alternative?"Humanity
A
1

You can use the setSelectionRange API to manually manipulate the textarea's selection. Get the original values from textarea.selectionStart and textarea.selectionEnd.

Aedes answered 14/10, 2018 at 22:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.