Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 966
12Me21 Avatar asked Nov 08 '22 03:11

12Me21


1 Answers

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

like image 177
Jimmy Breck-McKye Avatar answered Nov 13 '22 03:11

Jimmy Breck-McKye