Is there a way to edit the contents of input or textarea using javascript, and so that this change is canceled using the "cancel" command of the browser (for example, ctrl-Z )?
I try to insert a string, such as "Foo {0} bar", into the value when I select, and if the user selects a range, the selected range is inserted into the string instead of "{0}".
For example, if textarea contains “Example 1 2 3” and the cursor is in “Example 1 | 2 3,” then the function will change the value to “Example 1Foo blah bar 2 3" ( valueIfNothingSelected blah "in this case). If the range is selected "1 2", the function will instead change the value to "Example Foo 1 2 bar 3".
In Chrome, I tested this feature and it does what it should, but I cannot undo the change using undo .
function insertTextAtCursor(text, valueIfNothingSelected) { var field = $('textarea[name="task_log_description"]')[0]; var startPos = field.selectionStart; var endPos = field.selectionEnd; var processedText; if (startPos == endPos) { processedText = text.replace('{0}', valueIfNothingSelected); field.value = field.value.substring(0, startPos) + processedText + field.value.substring(endPos, field.value.length); field.selectionStart = startPos + text.indexOf('{0}'); field.selectionEnd = field.selectionStart + valueIfNothingSelected.length; } else { var selectedText = field.value.substring(startPos, endPos); processedText = text.replace('{0}', selectedText); field.value = field.value.substring(0, startPos) + processedText + field.value.substring(endPos, field.value.length); field.selectionStart = startPos + text.indexOf('{0}'); field.selectionEnd = field.selectionStart + selectedText.length; } field.focus(); }
javascript forms undo-redo
Martin carney
source share