Caret position calculated incorrectly in textarea.

J

j_macaroni

I found this code to calculate the caret position in a textarea. In the
script getCaret below, I pass it the TextArea1 element.
It seems to work until you press a CR. In which case you get the wrong
result because of this line: "textEl.caretPos.move("character",1)==1 )
--i; "

So now if you have 3 lines and you are at line 0, column 0 it shows a
5. I believe the move() method skips over CR/LF but
"textEl.value.length+1;" includes the CR/LF.

I know it has to do with CR/LF. Can anyone suggest how to fix this?
Thanks.

<html>
<body>
<script language=javascript>
function getCaret (textEl) {
if (textEl.createTextRange) {
textEl.caretPos = document.selection.createRange().duplicate();
var i=textEl.value.length+1;
while ( textEl.caretPos.parentElement() == textEl
&& textEl.caretPos.move("character",1)==1 ) --i;
return (i==textEl.value.length+1?-1:i);
}
}
</script>

<input name=caretPos type=text />
<TEXTAREA name="TextArea1"
style="position:absolute;left:64px;top:112px;width:816px;height:209px;z-index:2"
rows=10 cols=79
id="TEXTAREA1"
ONSELECT="document.main.caretPos.value=getCaret(this);"
ONCLICK="document.main.caretPos.value=getCaret(this);"
ONKEYUP="document.main.caretPos.value=getCaret(this);" >
</TEXTAREA>
</body>
</html>
 
J

j_macaroni

forgot the form name=main.

<form name=main>
<input name=caretPos type=text />
<TEXTAREA name="TextArea1"
style="position:absolute;left:64px;top:112px;width:816px;height:209px;z-ind­ex:2"

rows=10 cols=79
id="TEXTAREA1"
ONSELECT="document.main.caretPos.value=getCaret(this);"
ONCLICK="document.main.caretPos.value=getCaret(this);"
ONKEYUP="document.main.caretPos.value=getCaret(this);" >
</TEXTAREA>
</form>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top