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?
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.
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 .
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).
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With