12Me21
12Me21

Reputation: 1169

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

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.

Upvotes: 6

Views: 526

Answers (1)

Jimmy Breck-McKye
Jimmy Breck-McKye

Reputation: 3034

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

Upvotes: 1

Related Questions