Jump to content

set focus in a textbox at last cursor position


lonewolf217

Recommended Posts

I have the following code that I found online and modified slightly to fit my needs

 

It is for entering BBCode into a textarea field and it works fine, except for the fact that every time something is entered, the focus switches to the top of the text box.  Can someone help me figure out how to keep the focus at the point where the text was entered ?

 

<script type="text/javascript">
function insert(tag1,tag2) {
field = document.forms["form"].elements["desc"];
//IE SUPPORT
if(document.selection) {
field.focus();
sel = document.selection.createRange();
sel.text = tag1 + sel.text + tag2;
}
//MOZILLA/NETSCAPE SUPPORT
else if (field.selectionStart || field.selectionStart == '0') {
var startPos = field.selectionStart;
var endPos = field.selectionEnd;
field.value = field.value.substring(0, startPos)
+ tag1 + field.value.substring(startPos,endPos) + tag2
+ field.value.substring(endPos, field.value.length);
} 
//if nothing was selected, just insert at current cursor position
else {
var txt = document.forms["form"].elements["desc"];
txt.value+=tag;
}
}
</script>

Perhaps this will be of use to you..

 

function setCaretToEnd (input) {
  setSelectionRange(input, input.value.length, input.value.length);
}

 

Taken from: http://www.faqts.com/knowledge_base/view.phtml/aid/13562

 

There's a few other functions there that look like they may be of use as well!

 

Adam

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.