2

I am trying to get the user selected text in a text input when a button is clicked. This what I am trying:

<head>
    <script type="text/javascript">
        function GetSelectedText () {
            if (window.getSelection) {  // all browsers, except IE before version 9
                var range = window.getSelection ();                                        
                alert (range.toString ());
            } 
            else {
                if (document.selection.createRange) { // Internet Explorer
document.getElementById("foo").focus();
                    var range = document.selection.createRange();
                    alert (range.text);
                }
            }
        }
    </script>
</head>
<body>
    <button onclick="GetSelectedText ()">Get the selected text!</button>
    <input type = 'text' id = 'foo' />12345
</body>

It works as expected in all browsers, except IE9. In IE9, if you select some text from the 12345 chunk and press the button, the selected text is alerted all right. However, if you type something in the text input, select some of it, and click the button, a blank alert is generated.

Can anyone tell me how do I get it working in IE9? And is there any way to get the cursor position of the selection start as well (something like Mozilla's selectionStart)? Iam looking for Javascript solution, without Rangy or other related jQuery libraries..

SexyBeast
  • 7,913
  • 28
  • 108
  • 196

3 Answers3

2

Text inputs and textareas have a separate selection API, namely selectionStart and selectionEnd properties of the input itself. These are not supported in IE <= 8, but you already have the alternative for those.

Here's an implementation of your GetSelectedText() function that works in all major browsers:

Demo: http://jsfiddle.net/UK8gA/

Code:

function GetSelectedText() {
    var selectedText = "";
    var input = document.getElementById("foo");
    var sel, val = input.value;
    input.focus();
    if (typeof input.selectionStart == "number") {
        selectedText = val.slice(input.selectionStart, input.selectionEnd);
    } else if ( (sel = document.selection) && sel.createRange) { // IE
        var range = document.selection.createRange();
        selectedText = range.text;
    }
    alert(selectedText);
}
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Well, what did you do differently? You are also using `document.selection.createRange()` and then `range.text` to get the text.. – SexyBeast Feb 26 '13 at 07:05
  • Never mind, got it. Can you tell me whether there is any way to get the starting cursor position as well? (I think there is, `Rangy` does it, after all!) – SexyBeast Feb 26 '13 at 07:36
  • @Cupidvogel: `selectionStart` is what you need. The workaround for old IE is a bit tricky with line breaks. http://stackoverflow.com/a/3373056/96100 is one example. – Tim Down Feb 26 '13 at 09:34
  • Hi Tim, have you observed one thing, that if you replace the button by say a `p`, and attach the clickhandler to it, only a blank pop up is alerted in IE9? – SexyBeast Feb 27 '13 at 16:07
  • @Cupidvogel: Yes. This happens in all versions of IE because the selection is destroyed by the time the `click` event fires. You can get round this by making the element being clicked unselectable (using `unselectable="on"` in IE) or by handling the `mousedown` event instead. – Tim Down Feb 27 '13 at 17:34
  • @Cupidvogel: I think buttons just behave differently. If a user clicks on a button, it is unlikely that they intended to start making a selection. If the user instead clicks on a piece of regular content, they could be trying to deselect the current selection, or be initiating a new selection. – Tim Down Feb 27 '13 at 23:39
0

You can take a look at the jQuery Caret plugin: jCaret

// Get start pos in intput box with id="box1"
$("#box1").caret().start

// Get end pos
$("#box1").caret().end

// Get selected text
$("#box1").caret().text
Bagata
  • 2,120
  • 4
  • 25
  • 39
0

It all looks good except that the line "document.getElementById("foo").focus();" does not appear to be necessary and is probably why the browser is unable to detect the highlighted text. Try to remove it and see what you get.

KJ Price
  • 5,774
  • 3
  • 21
  • 34