update textarea value, but keep cursor position

Viewed 16024

I have an html textarea that will be updated periodically via javascript.

when I do this:

$("#textarea").val(new_val);

The cursor moves to the end of the text.

I would like to update the text without changing the cursor position. Also, if the user has a range of text selected, the highlight should be preserved.

2 Answers

A decade later but this is what I came up with for replacing items in a textarea. Some additional handling is needed to adjust the caret or selection when replacing with longer or shorter text.

// find and replace in textarea while preserving caret and selection
function replaceText(el, findText, replaceWithText) {
    var text = el.value;
    var selectionStart = 0;
    var selectionEnd = 0;
  // only support modern browsers for preserving caret and selection
    if (el.setSelectionRange) {
        selectionStart = el.selectionStart;
        selectionEnd = el.selectionEnd;
    }
    var start = 0;
    while ((start = text.indexOf(findText, start)) > -1) {
        var end = start + findText.length;
        text = text.substr(0, start) + replaceWithText + text.substr(end);
        if (selectionStart < end) {
            selectionStart = Math.min(selectionStart, start + replaceWithText.length);
        } else {
            selectionStart = selectionStart + replaceWithText.length - (end - start);
        }
        if (selectionEnd < end) {
            selectionEnd = Math.min(selectionEnd, start + replaceWithText.length);
        } else {
            selectionEnd = selectionEnd + replaceWithText.length - (end - start);
        }
        start += replaceWithText.length;
    }
  // don't do anything unless we need to (otherwise destroys undo)
    if (el.value != text) { 
        el.value = text;
        if (el.setSelectionRange) {
            el.selectionStart = selectionStart;
            el.selectionEnd = selectionEnd;
        }
    }
}
Place caret on or after the word LONGER, or select some text after or including it:
<br />
<textarea id='t'>Here is
some LONGERtext
to replace</textarea>
<br />
<input type="button" onclick="replaceText(document.getElementById('t'),'LONGER',''); document.getElementById('t').focus();" value="remove word LONGER" />

Related