简体   繁体   中英

How to replace selected text in a textarea with Javascript?

I have a textarea and a button which adds the following text to the textarea:

" - List Item "

If there is some text which is selected in the textarea, I would rather the text added to appear as so:

" - (selected text) "

So, the way to go about this would be to use an if function to see if there is text selected within the textarea and then if that is true, then receive the highlighted text so that it can be appended to the text in the textarea.

The appending part can simply be done by using document.getElementById(textarea).value += string but I'm unsure on checking if some of the text in the textarea is selected and receiving it.

For non IE browsers you can do something like this using selectionStart and SelectionEnd properties of textarea object:

function createListElement() {
    if(document.activeElement === textarea) {
        if(typeof textarea.selectionStart == 'number' && typeof textarea.selectionEnd == 'number') {
            // All browsers except IE
            var start = textarea.selectionStart;
            var end = textarea.selectionEnd;

            var selectedText = textarea.value.slice(start, end);
            var before = textarea.value.slice(0, start);
            var after = textarea.value.slice(end);

            var text = before + '- ' + selectedText + after;
            textarea.value = text;
       }
   }
}

But such a trivial manipulation is getting much harder for IE, you can find more here .

I hope this will help you :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM