How do I get window.getselection to work for an input type=text field

Freakishly picture Freakishly · Feb 21, 2011 · Viewed 8.3k times · Source

I have a contenteditable div, like so:

<div id="test" contentEditable="true" style="width: 600px; height:300px;">Lorem ipsum dolor sit amet</div>

for which I use the following code:

<input type="button" value="Click me" onclick="alert(window.getSelection().focusOffset.toString());"></button>

Clicking on the button when I move the caret around in the div, returns to me the actual position (offset) of the caret within the div.

The problem is when I replace the contenteditable div with an input type=text or password control, and keep the contenteditable property=true, and click on the button, I always get a zero. Why is this?

Thanks for looking.

Answer

Tim Down picture Tim Down · Feb 22, 2011

In most browsers, window.getSelection() only works with selections within text nodes and elements within the document. It doesn't apply to text within <input> and <textarea> elements (although in WebKit window.getSelection().toString() will return the selected text within a focussed text input or textarea. See http://jsfiddle.net/PUdaS/). To get the selection within an input, use the input's selectionStart and selectionEnd properties:

<input type="text" id="test" value="Some text">

<input type="button" value="Click me"
    onclick="alert(document.getElementById('test').selectionEnd);">

Note that IE up to and including version 8 does not support the selectionStart and selectionEnd properties, and a different, more complicated solution is required. IE doesn't support window.getSelection() either, so this code will work in all the browsers your original code does.