0

I'm trying to build a texteditor and for that I'm using a textarea to fill in my text

My problem is when I click a button the textarea selection is gone.

Here is some code to show the problem:

    <!DOCTYPE html>
    <html>
    <body>
    
    Address:<br>
    <textarea id="myTextarea">
    California Road
    </textarea>
    
    <p>Click the button to select the contents of the text area.</p>
    
    <button type="button">Try it</button>
    
    </body>
    </html>
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
NielsDePils
  • 241
  • 1
  • 2
  • 15

2 Answers2

0

If you want to add bbcode functionality you might want to have a look into this thread:

jQuery Set Cursor Position in Text Area

Also this code (taken from Tim Down in this thread Get the Highlighted/Selected text) might help:

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}
Community
  • 1
  • 1
Jochen Schultz
  • 456
  • 5
  • 16
0

The selection is not lost, but just not shown when textarea is not focused. Try this code on Firefox, Chrome or IE10: http://jsfiddle.net/swwqd700/

HTML part:

Address:<br>
<textarea id="myTextarea">
California Road
</textarea>    
<p>Click the button to select the contents of the text area.</p>
<button id="button">Try it</button>

Javascript part:

function go() {
    var e = document.getElementById("myTextarea");
    var startPos = e.selectionStart;
    var endPos = e.selectionEnd;
    var selection = e.value.substring(startPos, endPos)    ;
    alert("It seems to have disappeared, but...\n\"" + selection + "\"");
    e.focus();
}
var btn = document.getElementById("button");
btn.addEventListener(
    "click",
    go,
    false
);
Tolokoban
  • 2,297
  • 14
  • 17