17

I'm looking for a simple function (javascript / jquery) that checks whether or not ANY contents of a textarea is selected or highlighted... the function needs to return true or false.

Thanks :)

Tim
  • 6,986
  • 8
  • 38
  • 57
  • 2
    possible duplicate of [How to get selected text in textarea?](http://stackoverflow.com/questions/717224/how-to-get-selected-text-in-textarea) – Felix Kling Jan 30 '12 at 15:00
  • ^^ Google however, seems to do a good job answering ["check whether text selected in textarea".](http://www.google.co.uk/webhp?q=check+whether+text+selected+in+textarea&pbx=1&oq=check+whether+text+selected+in+textarea) – Matt Jan 30 '12 at 15:01
  • try http://www.codetoad.com/javascript_get_selected_text.asp – ghostCoder Jan 30 '12 at 15:01

1 Answers1

28

Try this

function isTextSelected(input){
   var startPos = input.selectionStart;
   var endPos = input.selectionEnd;
   var doc = document.selection;

   if(doc && doc.createRange().text.length != 0){
      return true;
   }else if (!doc && input.value.substring(startPos,endPos).length != 0){
      return true;
   }
   return false;
}

Usage

if(isTextSelected($('#textareaId')[0])){
   //text selected
}

Demo

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
  • 3
    if even unselect the text, it will continue returning selected! – thatsalok Dec 11 '13 at 11:03
  • I'm seeing the same behavior as stated by @thatsalok. I'll look for a solution, though – Brett Weber Jul 23 '14 at 19:10
  • @thatsalok - Because of the alert the text loses focus but stays selected. It does not look like it, but it is true. In the demo try to add this line after the alert $('#textareaId')[0].focus(); You will see your selection again. You can loose your selection, by making a selection of 0 characters ( in other words placing the cursor somewhere in the text area ). I made a fiddle update: http://jsfiddle.net/qDvYt/184/ – J.T. Houtenbos Jan 18 '17 at 17:44
  • @ShankarSangoli As of 2019, you can use latest one https://codepen.io/faizanrupani/pen/ZVwGyV – Faizan Anwer Ali Rupani Jan 14 '19 at 16:16