Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript check if text selected [closed]

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 :)

like image 969
Tim Avatar asked Jan 30 '12 14:01

Tim


People also ask

What is getSelection?

getSelection() method returns a Selection object representing the range of text selected by the user or the current position of the caret.

How do you know if a input field is selected?

You can be sure that no Selectable is selected (which includes InputFields) by simply checking this bool: Code (CSharp): EventSystem. current.

How do you highlight selected text in JavaScript?

getSelection() Method in JavaScript. The window. getSelection() method in JavaScript allows us to get the text highlighted or selected by the user on the screen. This method returns an object that contains information related to the text highlighted on the screen.


1 Answers

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

like image 124
ShankarSangoli Avatar answered Sep 21 '22 18:09

ShankarSangoli