469,621 Members | 1,685 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,621 developers. It's quick & easy.

cursor position in text box

AP
I am trying to find the integer value for the cursor position in a text box,
in particular I want to find out if I am at the end of some text that I
typed or at the beginning.

I am using IE 6.

Thanks,

Andy
Jul 23 '05 #1
2 28541
AP wrote:
I am trying to find the integer value for the cursor position in a text box,
in particular I want to find out if I am at the end of some text that I
typed or at the beginning.


The following will give you the position of the caret, the rest is a
matter of substring-ing the control value and determine whether the
position is the one required.

Few browsers support ranges, though; you can expect it to work on IE and
Mozilla, but probably no other agents yet. Limitations in supporting
browsers are to be sought in the function triggering (can you see
situations where the function won't be triggered while it should be?).
<form>
<input type="text" onkeyup="s(this)" onclick="s(this)">
<input type="text" name="position">
</form>

<script type="text/javascript">
function s(el){
var sel, rng, r2, i=-1;

if(typeof el.selectionStart=="number") {
i=el.selectionStart;
} else if(document.selection && el.createTextRange) {
sel=document.selection;
if(sel){
r2=sel.createRange();
rng=el.createTextRange();
rng.setEndPoint("EndToStart", r2);
i=rng.text.length;
}
} else {
el.onkeyup=null;
el.onclick=null;
}

el.form.elements["position"].value=i;
}
</script>
Jul 23 '05 #2
Ivo
"AP" wrote
I am trying to find the integer value for the cursor position in a text box, in particular I want to find out if I am at the end of some text that I
typed or at the beginning.

I am using IE 6.


That 's fine, but the question is what your users use. Incidentally, the
following code is 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;
}
// assuming document.f.txt is your textbox.

If the cursor is not in the textbox, the function returns a value of -1,
similar to the indexOf() method for strings.
HTH
Ivo
Jul 23 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

1 post views Thread by Tantra Veda | last post: by
1 post views Thread by objectref | last post: by
1 post views Thread by Andy Baxter | last post: by
reply views Thread by jnakam | last post: by
1 post views Thread by =?Utf-8?B?anAybXNmdA==?= | last post: by
reply views Thread by devrayhaan | last post: by
reply views Thread by gheharukoh7 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.