javascripthtmltextareaonselectselection-api

HTML5 how to get selected text out of a textarea


I was able to get the highlighted text out of a textarea by recording onselect and storing the beginning and end each time. Then, when I click a button, I build the substring myself. Isn't there a simpler way of simply querying the selection?

I was kind of expecting that there would be methods in html5 dom for all these things, something like:

textarea.getSelectedStart() textarea.getSelectedEnd(); textArea.setSelected(start,end);

Also, is there a way of programmatically deselecting text in a textarea?

I am putting in code based on the first solution below. This sort of works, but has a weird problem:

<script language=javascript>
function replaceCLOZE(code, questionType) {
  var v = code.value;
  var s = code.selectionStart;
  var e = code.selectionEnd;
  var t = v.substr(s, e-s);
  var rep = "{:" + questionType + ":="+t+"}";
  code.value = v.substr(0,s) + rep + v.substr(e,v.length-e+1);
}

function shortAnswer(code) {
  replaceCLOZE(code, "SA");
}
function shortAnswerCaseSensitive(code) {
  replaceCLOZE(code, "SAC");
}
function multipleChoice(code) {
  replaceCLOZE(code, "MC");
}

The text area does in fact have attributes code.selectionStart and code.selectionEnd. But the code above, which now works, sets the highlighted text on the screen to be the first word in the textarea. Mind you, the selectionStart is still correct, but what is actually highlighted in Firefox is wrong.

In Chrome it works fine. Maybe this is just a bug in firefox or is there something else which should be done to properly update the textarea visually?


Solution

  • Following is simple way to get selected text of textarea of html. Still not clear what you want as following method simply will give you selected text in alert.

    <html><head>
    <script>
    function alertme(){
    var textarea = document.getElementById("textArea");  
    var selection = (textarea.value).substring(textarea.selectionStart,textarea.selectionEnd);
    alert (selection);
    }
    
    </script>
    
    </head>
    <body> 
    <p><textarea class="noscrollbars" id="textArea"></textarea></p>
    <button onclick="alertme()">Click me</button>
    </body></html>
    

    When you select text, the button will alert you what you have selected. selectionStart gives you starting point and selectionEnd gives you end point, while substring needs three arguments string, starting point and ending point.