Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to insert text in textarea and update undo/redo queue?

A few days ago, I posted a question regarding how to update text in Internet Explorer. As it appears, the method used doesn't also works in Firefox.

This made me thinks if there is a way to modify the value of a textarea and update the undo/redo queue as well (calling ctrl-Z or document.execCommand('undo');)

So far, I have found two possibilities, but they don't work in all the browsers :

Option 1:

var event = document.createEvent('TextEvent');
event.initTextEvent('textInput', true, true, null, text, 9, "en-US");
textarea.focus();
textarea[0].setSelectionRange(selection.start, selection.end);
textarea[0].dispatchEvent(event);

Note: Doesn't seems to work in IE (at all) and Firefox

Option 2 :

document.execCommand("insertText", false, "the text to insert");

Doesn't work in IE (tested under 9, but seems to not be implemented at all), I don't know for the others browsers.

like image 635
Cyril N. Avatar asked Nov 06 '13 14:11

Cyril N.


2 Answers

The solution I come up so far is this one, but I'm open for betters ideas :

I check for the existence of the insertText via document.queryCommandSupported. If it does exists, I use it. If not, I simply replace the text :

var text = "hello world",
    textarea = jQuery("textarea"),
    selection = {'start': textarea[0].selectionStart, 'end': textarea[0].selectionEnd};

if (document.queryCommandSupported('insertText')) {
    document.execCommand('insertText', false, text);
}
else {
    textarea.val(textarea.val().substring(0, selection.start) + text + textarea.val().substring(selection.end, textarea.val().length));
}
like image 53
Cyril N. Avatar answered Oct 17 '22 01:10

Cyril N.


Option 1 works well as of now (8/19/2016), but is deprecated in Chrome for one of the upcoming releases. Dispatching the event generates the following warning:

A DOM event generated from JavaScript has triggered a default action inside the browser. This behavior is non-standard and will be removed in M53, around September 2016. See https://www.chromestatus.com/features/5718803933560832 for more details.

like image 21
Michal Filip Avatar answered Oct 17 '22 00:10

Michal Filip