How to get range of selected text of textarea in JavaScript

14,536

Solution 1

Use the code below or check this fiddle

   function getTextSelection(el) {
    var start = 0, end = 0, normalizedValue, range,
        textInputRange, len, endRange;

    if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
        start = el.selectionStart;
        end = el.selectionEnd;
    } else {
        range = document.selection.createRange();

        if (range && range.parentElement() == el) {
            len = el.value.length;
            normalizedValue = el.value.replace(/\r\n/g, "\n");

            // Create a working TextRange that lives only in the input
            textInputRange = el.createTextRange();
            textInputRange.moveToBookmark(range.getBookmark());

            // Check if the start and end of the selection are at the very end
            // of the input, since moveStart/moveEnd doesn't return what we want
            // in those cases
            endRange = el.createTextRange();
            endRange.collapse(false);

            if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
                start = end = len;
            } else {
                start = -textInputRange.moveStart("character", -len);
                start += normalizedValue.slice(0, start).split("\n").length - 1;

                if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
                    end = len;
                } else {
                    end = -textInputRange.moveEnd("character", -len);
                    end += normalizedValue.slice(0, end).split("\n").length - 1;
                }
            }
        }
    }
    alert("start :" + start + " End :" + end);
}

Solution 2

While the original answer may have helped the OP in 2012, things have changed, and this has now become simpler, at least in modern browsers.

You can use the Javascript selectionStart and selectionEnd attributes of the textarea.

Basic Usage:

These are both standard attributes that will work in today's major browsers (Chrome, Safari, Firefox, Opera, Edge, IE).

For example:

console.log(document.getElementById("text").selectionStart,document.getElementById("text").selectionEnd)

will return both the start and end point of the selection in the textarea with the ID text.

Boundary Cases:

If there is no item selected in the textarea, then both the start and end attributes will return the last position of the caret. If the textarea has not recieved focus yet, the attributes will both return a value of 0.

Changing the Selection:

By setting these attributes to new values, you will adjust the active text selection. Thus, you can also use this to select text in a textarea.

Checking if a Selection is in Place:

You can check if there is currently a selection by checking if the values are both different, i.e. if

document.getElementById("text").selectionStart != document.getElementById("text").selectionEnd

is true, then there is a text selection.

References

Share:
14,536

Related videos on Youtube

user1619672
Author by

user1619672

Updated on September 15, 2022

Comments

  • user1619672
    user1619672 almost 2 years

    I am trying to retrieve/find the start point and end point of selection in textarea. Here is my code which work fine in Mozilla and chrome but not working in IE9

    <script type="txt/javascript">
        function update(o) {
    
                var t = o.value, s = getSelectionStart(o), e = getSelectionEnd(o);
                alert("start :" + s + " End :" + e);
            }
    
            function getSelectionStart(o) {
                if (o.createTextRange) {
                    var r = document.selection.createRange().duplicate()
                    rse = r.text.length;
                    r.moveEnd('character', o.value.length)
                    if (r.text == '') return o.value.length
                    return o.value.lastIndexOf(r.text)
                } else return o.selectionStart
            }
    
            function getSelectionEnd(o) {
                if (o.createTextRange) {
                    var r = document.selection.createRang;e().duplicate()
                    r.moveStart('character', -o.value.length)
                    return r.text.length
                } else return o.selectionEnd
            }
    </script>
    
    <textarea id ="text" rows=10 cols="50" onselect="update(this);"></textarea>
    

    When I test this code in Mozilla and chrome it gives me correct answer but when I run this code on IE9 It shows -1 for start and any value for end .

    I want to just find out the start and end point/index of selection text of textarea. Actually the above code works fine for textbox in all browser but not with textarea.

    Please suggest me ...

  • user1619672
    user1619672 almost 12 years
    Thanks for help its working fine in chrome, mozila but In IE9 it shows me end value wrong. Start value showing correct but end value is not could you please check again...
  • tsergium
    tsergium almost 12 years
    Sorry for not double checking the code. Couldn't get your example to work so I found the answer elsewhere. I hope this helps you (I edited the previous code).
  • user1619672
    user1619672 almost 12 years
    Thanks yaar its working thanku very much you are genius.. It showing me perfect ans in every browser.
  • Hrvoje Golcic
    Hrvoje Golcic over 9 years
    Any idea on how to achieve this not only in <textarea> but in various elements such as <p> ? Thanks
  • Josué Zatarain
    Josué Zatarain almost 5 years
    Be aware that this works in IE <9, not in modern browsers.
  • Diode Dan
    Diode Dan about 4 years
    This is a better, more modern answer for modern browsers