...

View Full Version : How do I keep the cursor position after the " has been replaced with "?



Jodarecode
07-16-2010, 09:33 PM
Here is my example code


<html>
<head>
</head>
<body onload="addtext()">

How do I keep the cursor position after the " has been replaced with &amp;quot;?<br><br>
<form name="update" id="update" method="post" action="">
<textarea name="description" id="description" value="" cols="55" rows="15" onKeyUp="addtext()">Type a quote here[] and see the cursor move to the end here:</textarea>
<br>
Result:<br>
<div name="outputtext" id="outputtext"></div>
</form>

</body>
<script language="javascript" type="text/javascript">
function addtext() {
var newtext = document.update.description.value;
document.getElementById('outputtext').innerHTML = newtext.replace(/\r\n|\n/g,"<br />");
document.getElementById('description').value = newtext.replace(/"/g,"&quot;");
}
</script>
</html>

gusblake
07-18-2010, 01:52 AM
For Firefox: the cursor position at the time of the function call is document.update.description.selectionStart.

To move it back you use setSelectionRange(start, end).

Eg.



function addtext() {
var newtext = document.update.description.value;
var curpos = document.update.description.selectionStart;
document.getElementById('outputtext').innerHTML = newtext.replace(/\r\n|\n/g,"<br />");
document.getElementById('description').value = newtext.replace(/"/g,"&quot;");
document.update.description.setSelectionRange(curpos+6, curpos+6);
}


The +6 here accounts for the length of the replacement.

Getting it to work in IE is a bit more complicated, http://parentnode.org/javascript/working-with-the-cursor-position/ might be of some help to you.

Jodarecode
07-21-2010, 12:22 AM
It seems to work ok after I had changed:

document.update.description.setSelectionRange(curpos+6, curpos+6);
to:

document.update.description.setSelectionRange(curpos+0, curpos+0);

Also when I type text to the point it pulls up the overflow scroll bar,
the scroll bar scrolls to the top when I hit enter and cannot see what I am typing.
I tried return false and still no go, any ideas?



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum