Javascript: Get Selected/Highlighted Text from a TextArea Using Javascript and jQuery

9/30/2015 1:40:13 PM

The following code will allow you to determine what text is selected or highlighted. It uses jQuery to grab the DOM objects and check the selection indices. If no text is selected, the indices will be the same.

<textarea style="width: 400px; height: 200px;" id="txtBody"></textarea>

<button id="butWhatIsSelected">What is selected</button>

<script type="text/javascript">

    $("#butWhatIsSelected").click(function ()
    {
        var fullText = $("#txtBody").val();
        var selected_text_index_start = $("#txtBody")[0].selectionStart;
        var selected_text_index_end = $("#txtBody")[0].selectionEnd;
        var selected_text = fullText.substring(selected_text_index_start, selected_text_index_end);        

        //log indices
        console.log(selected_text_index_start + "," + selected_text_index_end);

        //check if any selection made
        if (selected_text_index_start == selected_text_index_end)
        {
            console.log("no text selected");
        }
        else
        {            
            console.log(selected_text);
        }
    });

</script>