Jump to content

Getting the current position of a cursor in a text box


trink

Recommended Posts

Say a user has their cursor in a text box and they click a button and want to add some information in, how would I get the current position of the cursor in the textbox to add that information in to that specific place?

 

Any help would be greatly appreciated.

Link to comment
Share on other sites

I did not write this javascript function by myself so i take no responsability :P. Hope it works anyway.

 

With 'el' being your form control, try using:

function getCaretPos(el) {
var rng, ii=-1;
if(typeof el.selectionStart=="number") {
ii=el.selectionStart;
} else if (document.selection && el.createTextRange){
rng=document.selection.createRange();
rng.collapse(true);
rng.moveStart("character", -el.value.length);
ii=rng.text.length;
}
return ii;
}

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.