How to put inside a variable only the text that was selected inside a textarea?

4

With

var texto = document.getElementById('texto').value;

I get everything that is in the tetxarea that has this id, but what if I want a partial text?

For example the whole text is this:

Germany bought the game against Brazil

If I just select "bought the game", I would like my var to have this content.

Added (11/5/15):

Well, with the mouseup the alert works, but so, if I simply need to put the value of the selection inside a variable with

 var textoSelecionado = showSelection(this);

Then try to use this value?

My final goal is to be able to place HTML tags around the selected text.

However, if I click on the link / image / button that performs this function, the text will no longer be selected and, by testing the "showSelection" function, will no longer be effective.

I figured out a way to make this functional: activating and deactivating the buttons, then if they are active when selecting the text in the "mouseup" it undergoes the changes. If they do not have assets they do not change. It would be like controlling whether or not to use the showSelection function. This I think I can do, but I would like to retain the selected text to use it by clicking a button or link.

    
asked by anonymous 10.05.2015 / 23:15

1 answer

5

I found an answer in SOen that I adapted. So with this function you can go get what is selected.

HTML

<textarea name="" id="texto" cols="30" rows="10">Texto de exemplo</textarea>

JS

function showSelection(textComponent) {
    var selectedText;
    // IE version
    if (document.selection != undefined) {
        textComponent.focus();
        var sel = document.selection.createRange();
        selectedText = sel.text;
    }
    // Mozilla version
    else if (textComponent.selectionStart != undefined) {
        var startPos = textComponent.selectionStart;
        var endPos = textComponent.selectionEnd;
        selectedText = textComponent.value.substring(startPos, endPos)
    }
    return selectedText;
}

var textarea = document.getElementById('texto');
textarea.addEventListener('mouseup', function () {
    var textoSelecionado = showSelection(this);
    if (textoSelecionado) alert(textoSelecionado);
});

jsFiddle: link

    
10.05.2015 / 23:17