views:

37

answers:

1

I have a caret in the textarea (no selection). I need to make selection out of it.
For example: "This is a te|xt"

var caret = document.selection.createRange (); // got empty range between "e" and "x"
caret.moveEnd('character'); // Move endpoint one character right, now it must be "x"
alert (caret.text); // empty !!!

What is wrong?

+2  A: 

You don't call "moveEnd" on the selection object - you call it on the TextRange ("caret"):

var caret = document.selection.createRange (); // got empty range between "e" and "x"
caret.moveEnd('character'); // Move endpoint one character right, now it must be "x"
caret.select(); // make the selection equal the range
alert (caret.htmlText);

edit I'm also editing this to make it so that the "alert" actually works :-)

Here is an example page: http://gutfullofbeer.net/range.html

I think this stuff might only work in IE by the way. (Confirmed that at least Chrome doesn't do anything with that code.)

Pointy
sorry, it is my fault, i just messed up here with variables names. Changed it. It is does not working.
Qiao
Try it now - I've fixed it again so that the stuff referenced in the "alert" actually works.
Pointy
nope, it is still does not working. First selection should be empty, just caret | .
Qiao
Try the page I did - look at the link in my answer.
Pointy
working. now I am looking what is wrong with my page.
Qiao
Be damned, IE! :) http://stackoverflow.com/questions/2369390/js-caret-to-selection-by-pressing-button-in-ie
Qiao