Forum Moderators: open

Message Too Old, No Replies

Inserting to a Textarea

Getting focus() to place cursor at insertion point.

         

createErrorMsg

8:31 pm on Mar 23, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm using an insertAtCursor() function (from Alex King [alexking.org]) to implement HTML quicktags in a CMS. I've got it working to insert the tags at the cursor location, but I'm also trying to get the script to place the focus back on the textarea at the location of the insert. I used the focus() method, which places focus back on the textarea, but in Firefox the cursor is placed at the end of the textarea's content, not at the insertion point.

Is there a way to get Firefox to insert the tag, then place focus back on the textarea with the cursor at the insertion point?


//creates code for anchortag, then inserts with insert function
function a(val) {
myValue = '';
if (val == 'open'){
myValue += "<a href='#' title='#'>";
} else {
myValue += "</a>";
}
insertAtCursor(myValue);
}

function insertAtCursor(myValue) {
myField = document.form1.text;
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
}
//MOZILLA/NETSCAPE support
else if (myField.selectionStart ¦¦ myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
} else {
myField.value += myValue;
}
document.form1.text.focus();
}

Thanks in advance.

cEM

oyejorge

7:00 pm on Apr 30, 2005 (gmt 0)

10+ Year Member



Yes! I found Alex's code very helpful, but also found it needed to replace the cursor where it started... here's what I've figured out and tested a little. So far it's worked fine, but if you find issues, please let me know.


function insertAtCursor(myField, myValue) {
//
//IE support
if (document.selection) {
myField.focus();
sel = document.selection.createRange();
sel.text = myValue;
myField.focus();
}
//
//MOZILLA/NETSCAPE support
else if (myField.selectionStart ¦¦ myField.selectionStart == '0') {
var startPos = myField.selectionStart;
var endPos = myField.selectionEnd;
var cursorPos = startPos + myValue.length;
//
myField.value = myField.value.substring(0, startPos)
+ myValue
+ myField.value.substring(endPos, myField.value.length);
//
myField.selectionStart = cursorPos;
myField.selectionEnd = cursorPos;
}else{
myField.value += myValue;
}
}