TextArea SelectedText, SelectionStart, SelectionEnd, SelStart, SelEnd (IE and FireFox)

Simple way of getting the html textarea’s selection properties selectedText, selectionStart, selectionEnd:

Javascript:

 function getTextAreaSelection() {
   var textArea = document.getElementById('textarea1');
   if (document.selection) { //IE
       var bm = document.selection.createRange().getBookmark();
       var sel = textArea.createTextRange();
       sel.moveToBookmark(bm);
     
       var sleft = textArea.createTextRange();
       sleft.collapse(true);
       sleft.setEndPoint("EndToStart", sel);
       textArea.selectionStart = sleft.text.length
       textArea.selectionEnd = sleft.text.length + sel.text.length;
       textArea.selectedText = sel.text;  
   }
   else if (textArea.selectionStart){ //FF
      textArea.selectedText = textArea.substring(textArea.selectionStart,textArea.selectionEnd);
   }
  
   alert("Selection Start==> " + textArea.selectionStart + "\n" +
      "Selection End  ==> " + textArea.selectionEnd + "\n" +
      "Selected Text  ==> " + textArea.selectedText + "\n" +
      "TextArea Value ==> " + textArea.value);
 }

HTML:

<textarea id="textarea1"></textarea> <button onclick="getTextAreaSelection()">Get Selection Info</button>
Advertisements