Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 928
Freakishly Avatar asked Feb 21 '11 22:02

Freakishly


Video Answer


2 Answers

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.

like image 68
Tim Down Avatar answered Sep 20 '22 13:09

Tim Down


This will largely depend on the browser you are using, as this is a quirk of browser design and not JavaScript.

What happens in your case is when you click an <input type="button"> while having a <div> highlighted, the <div> remains highlighted. However, when you click an <input type="button"> while having an <input type="text"> or <textarea> highlighted, they lose focus and the highlight is removed (thus making your code fail).

I would take a closer look at what you are trying to accomplish and consider rethinking how you are approaching this problem.

like image 31
Moses Avatar answered Sep 22 '22 13:09

Moses