Login or Sign up Help | Site Map
Connecting Tech Pros Worldwide

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

Question posted by: charly (Guest) on July 20th, 2005 10:34 AM
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);"[color=blue]
>[/color]
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);"[color=blue]
>[/color]
</form>

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

any ideas ?

Would you like to answer this question?
Sign up for a free account, or Login (if you're already a member).
Ivo's Avatar
Ivo
Guest
n/a Posts
July 20th, 2005
10:36 AM
#2

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

"charly" <kanari667@yahoo.fr> wrote in message
news:3f6ad147$0$27596$626a54ce@news.free.fr...[color=blue]
> Is it possible to get the cursor's position in an input text?[/color]

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




charly's Avatar
charly
Guest
n/a Posts
July 20th, 2005
10:37 AM
#3

Re: get a a char's position when its string is clicked
Works great with Ie. Didn't know about the createTextRange,
parentElement stuff

Thank you very much !


 
Not the answer you were looking for? Post your question . . .
169,970 Experts ready to help you find a solution.
Sign up for a free account, or Login (if you're already a member).

  • Didn't find the answer you were looking for?
    Post Your Question
  • Top Community Contributors