javascript - update textarea value, but keep cursor position -
Get link
Facebook
X
Pinterest
Email
Other Apps
I have HTML Texresia which will be updated from time to time via javascript.
When I do this: / P>
$ ("# textarea"). Val (new_val);
The cursor goes to the end of the text.
I want to update the text without changing the cursor's position. Also, if the user has a range of text, the highlight should be preserved.
here is one
Note: If you are interested in IE & lt; If there is no need to support = 8, then just use , select Start and selectEnd attribute ().
getInputSelection (l) {var start = 0, end = 0, normalizedValue, range, textInputRange, len, endRange are all complex code below. ; If (el.selectionStart == "number" & type; el.selectionEnd == "number") (start = el.selectionStart; end = el.selectionEnd;} Else {range = document.selection.createRange () ; If (range & amp; amp; amp;; amp; .Element () == l) {len = el.value.length; generalized value = el.value.replace (/ \ r \ n / g , "\ N"); // Create a working text range that only resides in input text InputRange = el.createTextRange (); textInputRange.moveToBookmark (range.getBookmark ()); // Check whether the selection starts And the end is at the end of the input, as the moveStart / moveEnd does not return to those cases, which we want // Range = el.createTextRange (); endRange.collapse (wrong); if (textInputRange.compareEndPoints ("StartToEnd", endorange)> -1) {start = end = len;} and {start = -textInputRange.moveStart ( "Character", -len); Start + = normalizedValue.slice (0, start) .split ("\ n"). Length-1; if (text inputrange codeparency point points ("endound", endrange)> 1) {End = len;} and {end = -textInputRange.moveEnd ("character", -n); End = normalized value (0, end) .split ("\ n") Length - 1; }}}} Return {start: start, end: end}; } OffsetToRangeCharacterMove (L Offset) {Offset Return - (el.value.slice (0, Offset) .split ("\ r \ n") Length - 1); } Input selection (L, offoffice, and offset) set to function {type (typef.l.SessionStart == "number" and L.selectionEnd == "number") {el.selectionStart = startOffset; El.selection end = and offset; } And {var category = el.createTextRange (); Var startCharMove = offsetToRange sensor main (al, startoffset); Range.collapse (true); If (startoffset == endOffset) {range.move ("character", startCharMove); } And {range.moveEnd ("character", offsettorangcharactermov (L, endoffet)); Range.movest ("character", beginning of the month); } Category. Select (); }}
When you change the value of texture, first save the selection, then restore it later:
var t = document.getElementById ("Textarea"); Var sel = getInputSelection (t); T.value = some_new_value; SetInputSelection (t, sel.start, sel.end);
Comments
Post a Comment