By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,607 Members | 1,817 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,607 IT Pros & Developers. It's quick & easy.

get a a char's position when its string is clicked

P: n/a
Greetings,

I got the following problem :

I have a input text which holds the following value : hello

Now, when the user click on the first l, a window.alert pops up and
prints 3.

Question : Is it possible to get the cursor's position in an input text?
Note I said input text, not a textarea.

So far, I've found this :
<html>
<head>
<script>
function storeCaret (textEl) {
if (textEl.createTextRange)
textEl.caretPos = document.selection.createRange().duplicate();

}
function insertAtCaret (textEl, text) {

if (textEl.createTextRange && textEl.caretPos) {
var caretPos = textEl.caretPos;
alert(caretPos.text.length - 1);
caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' '
? text + ' ' : text;

}
else
textEl.value = text;
}
</SCRIPT>
</head>
<body>

<form NAME="aForm">
<textarea NAME="aTextArea" ROWS="5" COLS="80" WRAP="soft"
ONSELECT="storeCaret(this);"
ONCLICK="storeCaret(this);"
ONKEYUP="storeCaret(this);"
Kibology for all.
All for Kibology.
</textarea>
<br>
<input TYPE="text" NAME="aText" SIZE="80" VALUE="Scriptology">
<br>
<input TYPE="button" VALUE="insert at caret"
ONCLICK="insertAtCaret(this.form.aTextArea,
this.form.aText.value);"

</form>

</body>
</html>
But I cannot the char's position

any ideas ?

Jul 20 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Ivo

"charly" <ka*******@yahoo.fr> wrote in message
news:3f***********************@news.free.fr...
Is it possible to get the cursor's position in an input text?


Try this function (IE only):

function caretPos(){
var i=document.f.txt.value.length+1;
if (document.f.txt.createTextRange){
theCaret = document.selection.createRange().duplicate();
while (theCaret.parentElement()==document.f.txt &&
theCaret.move("character",1)==1) --i;
}
return i==document.f.txt.value.length+1?-1:i;
}

You 're lucky you have an input. I use this function in a textarea, and if
my cursor is at the 345th position, it takes quite a while for the while
loop on line 5 to reach the end.
HTH
Ivo

Jul 20 '05 #2

P: n/a
Works great with Ie. Didn't know about the createTextRange,
parentElement stuff

Thank you very much !

Jul 20 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.