Forum Moderators: open
Everything works fine in Safari and Mozilla, but IE (tested with 6.0) is being troublesome.
I *almost* have it working, but when there are newlines in the box, it messes up the cursor placement.
The relevant code is below.
var sel = document.selection.createRange();// Get current cursor point
var storedRange = sel.duplicate();
storedRange.moveToElementText(myField);
storedRange.setEndPoint('EndToEnd', sel);
var cursorPoint = storedRange.text.length - sel.text.length + edButtons[i].tagStart.length;
// Add the text
sel.text = edButtons[i].tagStart + edButtons[i].tagEnd;
// This seems to work, but breaks when you have newlines/linebreaks in the textarea
var textRange = myField.createTextRange();
textRange.collapse(true);//go to beginning of range
textRange.moveEnd('character', cursorPoint);
textRange.moveStart('character', cursorPoint);
textRange.select();
[edited by: DrDoc at 11:18 pm (utc) on Feb. 11, 2006]
The following little bit of code return interesting results that might explain your incorrect cursor placment:
<html><head><title>test</title>
<script>
function count(){
alert(document.getElementById('textfield').value.length);
}
</script>
</head>
<body>
<textarea id="textfield">
line
line</textarea>
<input type="submit" onclick="count()">
</body></html>
Firefox 1.5.0.1 returns 9
Internet 7 beta 2 returns 10
I can't definitely say what causes this but I would guess that Internet Explorer counts newlines as two characters.
Hope that helps.
Andrew
I think I was right about IE treating newlines as 2 characters, see example
<html><head><title>test</title>
<script>
function count(){
var elem = document.getElementById('textfield').value;
for(i=0;i<elem.length;i++){
alert(elem.charAt(i));
}
}
</script>
</head>
<body>
<textarea id="textfield">
line
line</textarea>
<input type="submit" onclick="count()">
</body></html>
IE gives you 2 blank messages, firefox 1.
PS. if found this site don't know if it's any use,
http://the-stickman.com/web-development/javascript/finding-selection-cursor-position-in-a-textarea-in-internet-explorer/ [the-stickman.com]
<html><head><title>test</title>
<script>
function count(){
var elem = document.getElementById('textfield').value;
var r = "";
for (i=0;i<elem.length;i++) {
if (elem.charAt(i)!= '\r') {
r += elem.charAt(i);
}
}
alert(r.length);
for(j=0;j<elem.length;j++){
alert(r.charAt(j));
}
}
</script>
</head>
<body>
<textarea id="textfield">
line
line</textarea>
<input type="submit" onclick="count()">
</body></html>