Search code examples
javascriptjqueryrangy

Get Selected Text on HTML page using jQuery


I have a simple HTML page where I want the selected text inside text area to use it for some processing. I have written jQuery code but I am always getting empty string as selection. Please help me to fix this issue in my code.

HTML code is as given below:

<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
</head>
<body>
    <form action="#" id="formfirst">
        <textarea name="tafirst" rows="10" id="tafirst">Along came Polly ---- Reality Bites ---- Duplex ---- Walter Mitty </textarea>
        <br>
        <input type="text" id="txtfirst">
        <br>
        <input type="submit">
    </form>
</body>
<script type="text/javascript" src="js/verify.js"></script>
</html>

Javascript code is given below:(verify.js)

function getSelectedText(){
    var t = '';
    if(window.getSelection){
        t = window.getSelection();
    }else if(document.getSelection){
        t = document.getSelection();
    }else if(document.selection){
        t = document.selection.createRange().text;
    }
    return t;
}

$(document).ready(function(){  
    //alert("HERE 1");
});
$(document).keypress(function(e){   
    if($('#tafirst').is(':focus')){
        if(e.altKey && e.which==97){
            alert(getSelectedText());
            e.preventDefault();
        }
    }
});

EDIT

I have downloaded rangy plugin and put it inside my js folder. I have included that plugin in my HTML as given below:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="js/rangy/rangy-1.2.3/rangy-core.js"></script>
</head>
<body>
<form action="#" id="formfirst">
<textarea name="tafirst" rows="10" id="tafirst">Along came Polly ---- Reality Bites ---- Duplex ---- Walter Mitty </textarea>
<br>
<input type="text" id="txtfirst">
<br>
<input type="submit">
</form>
</body>
<script type="text/javascript" src="js/verify.js"></script>
</html>

Corresponding modified js file is as follows:

var range = rangy.createRange();

$(document).ready(function(){  
    alert(range);
    alert("HERE 1");    
});
$(document).keypress(function(e){   
    if($('#tafirst').is(':focus')){
        if(e.altKey && e.which==97){
            alert(getSelectedText());
            e.preventDefault();
        }
    }
});

But it is not even showing any alert message. Have I done anything wrong while adding rangy's js reference?


Solution

  • Getting selected text from a textarea requires a different API from getting the selected text in the main text of the page in most browsers. You should use the textarea's selectionStart and selectionEnd properties. This method will work for text inputs too:

    function getSelectedText(el) {
        var sel, range;
        if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
            return el.value.slice(el.selectionStart, el.selectionEnd);
        } else if (
                (sel = document.selection) &&
                sel.type == "Text" &&
                (range = sel.createRange()).parentElement() == el) {
             return range.text;
        }
        return "";
    }
    

    Example:

    function getSelectedText(el) {
      var sel, range;
      if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        return el.value.slice(el.selectionStart, el.selectionEnd);
      } else if (
        (sel = document.selection) &&
        sel.type == "Text" &&
        (range = sel.createRange()).parentElement() == el) {
        return range.text;
      }
      return "";
    }
    
    window.onload = function() {
      document.getElementById("ta").onselect = function() {
        alert("Selected text: " + getSelectedText(this));
      };
    };
    <textarea id="ta" rows="5" cols="50">Please select some text in here</textarea>