cursor position in text box

A

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
 
Y

Yann-Erwan Perio

AP said:
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>
 
I

Ivo

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
 

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,774
Messages
2,569,596
Members
45,132
Latest member
TeresaWcq1
Top