menu

Wednesday, November 19, 2014

Getting Selected Text of TextArea Using JavaScript

Getting Selected Text of TextArea Using JavaScript:

     You can get the selected text of a textarea using pure javascript. The below example shows how to achieve it. The example below tested with chrome, mozilla and ie with the following specified versions.Chrome version 38.0.2125.111, ie version 11.0.9600, mozilla version 32.0.3

Example:

     <html>
       <head>
<script type="text/javascript">
function getSelectedText() 
{
var txtArea = document.getElementById("textarea1");
var selectedText;   
if (txtArea.selectionStart != undefined)
{    
    var startPosition = txtArea.selectionStart;
    var endPosition = txtArea.selectionEnd;
     selectedText = txtArea.value.substring(startPosition, endPosition);
}
alert("You selected :" + selectedText);
}
</script>
</head>
<body>
<textarea id="textarea1" onselect="getSelectedText()" cols="75"  rows="30">
</textarea>
</body>
      </html>

The screen will look like the following.


Getting Selected Text of TextArea Using JavaScript
Figure 1

You can download the source code from here

No comments:

Post a Comment