2

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.

1 Answer 1

4

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

Short version: var t=textarea, s=t.selectionStart, e=t.selectionEnd, v=t.value; if(typeof s=='number' && typeof e=='number') t.value=v.slice(0, s)+'- '+v.slice(s, e)+v.slice(e);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.