If I got you correctly, this would be a solution.
Greetings
<html>
<body>
<form>
<textarea name="textfield">asdfasdfasdf</textarea>
</form>
<script>
var textObj = document.forms[0].elements["textfield"].value;
var textLength = textObj.length;
alert(textObj.substring(textLength-1,textLength))
</script>
</body>
</html>
> Could anyone show me how to programmatically retrieve (in JavaScript) the
> character located immediately before the current position of the cursor in
> the TEXTAREA object?
>
> Any help greatly appreciated.
Ivo - 30 Sep 2003 04:50 GMT
> > Could anyone show me how to programmatically retrieve (in JavaScript) the
> > character located immediately before the current position of the cursor in
[quoted text clipped - 3 lines]
> var textLength = textObj.length;
> alert(textObj.substring(textLength-1,textLength))
That returns the last character in the textarea. This function returns the
index of the current cursor position (but takes a looong time if it is above
200):
function caretPos(){
var i=document.forms[0].elements["textfield"].value.length+1;
if (document.forms[0].elements["textfield"].createTextRange){
theCaret = document.selection.createRange().duplicate();
while (theCaret.parentElement()==document.forms[0].elements["textfield"]&&
theCaret.move("character",1)==1) --i;
}
return i==document.forms[0].elements["textfield"].value.length+1?-1:i;
}
so if there is indeed a cursor in the textarea,
document.forms[0].elements["textfield"].value.charAt(caretPos()-1) should be
your answer. I believe createRange() is IE only.
HTH
Ivo