Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I delete text in a textarea in such a way that it gets entered in the native edit history?

I have a sort of mini-app that, amongst other things, manually modifies an input textarea. Simply setting the value (and optionally restoring cursor/scroll position) has one big drawback: it scrambles the edit history. So I use this function for all modifications:

function type(el, str) {
    var e = document.createEvent('TextEvent');
    e.initTextEvent('textInput', true, true, null, str);
    el.dispatchEvent(e);
}

The poor support is OK for my project, and the function works great for inserting text and for replacing it (select the text you want replaced, then call type). But when it's called with an empty string, it does nothing at all.

For some deletions I can work around this by selecting both the text I want to delete and something extra, re-typing the extra bit, then moving the cursor appropriately. But that's impossible if we're deleting everything in the textarea.

So does anybody know of a workaround, or some other way to modify the textarea's value without messing up the edit history?

like image 816
st-boost Avatar asked Jan 01 '13 20:01

st-boost


People also ask

How do you delete textarea text?

To clear the value of a textarea element, set it's value property to an empty string, e.g. textarea. value = '' . Setting the element's value to an empty string removes any of the text from the element.

How do you delete text input history?

That solution helped me: if you are using google Chrome, try this: Put the mouse pointer on the entry that you want to delete, press Delete . If the entry is not removed, press Shift + Delete .

What is the use of textarea control?

The <textarea> tag defines a multi-line text input control. The <textarea> element is often used in a form, to collect user inputs like comments or reviews. A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).


1 Answers

Instead of passing in an empty string, pass in \0. That seemed to work here. Or you can just detect an empty string like this:

function type(el, str) {
    var e = document.createEvent('TextEvent');
    e.initTextEvent('textInput', true, true, null, str || "\0");
    el.dispatchEvent(e);
}
like image 128
jeremy Avatar answered Nov 14 '22 21:11

jeremy