S
Shmuel
Hi,
I'm trying to get a caret postion and the current character from a text
field. I just can't get the current character right.
The caret position I get alright but the problem is when I want to
return that character. If I set the pos manually, then I can get it
alright, but if I set it to something else I don't get anything back.
I'd appreceiate if someone could test this code and suggest me any
solution.
Here is the code:
// assume IE and textfield (not textarea)
function getCursorPosition2(textarea) {
var txt = textarea.value;
var len = txt.length;
var pos = -1;
range_sel = document.selection.createRange();
range_obj = textarea.createTextRange();
range_obj.moveToBookmark(range_sel.getBookmark());
range_obj.moveEnd('character', textarea.value.length);
pos = (len - range_obj.text.length);
if(pos != -1) {
len = txt.length + 1;
alert(document.all.text.value.charAt(pos));
return pos;
}
}
Here is a code for a form:
<html>
<head>
<script src="numberFormat.js"></script>
</head>
<body>
<form name="form" action="<? $_SERVER['PHP_SELF'] ?>">
Test: <input type="text" name="text"
onkeypress="window.status=getCursorPosition2(text)"><br>
</form>
</body>
</html>
I'm trying to get a caret postion and the current character from a text
field. I just can't get the current character right.
The caret position I get alright but the problem is when I want to
return that character. If I set the pos manually, then I can get it
alright, but if I set it to something else I don't get anything back.
I'd appreceiate if someone could test this code and suggest me any
solution.
Here is the code:
// assume IE and textfield (not textarea)
function getCursorPosition2(textarea) {
var txt = textarea.value;
var len = txt.length;
var pos = -1;
range_sel = document.selection.createRange();
range_obj = textarea.createTextRange();
range_obj.moveToBookmark(range_sel.getBookmark());
range_obj.moveEnd('character', textarea.value.length);
pos = (len - range_obj.text.length);
if(pos != -1) {
len = txt.length + 1;
alert(document.all.text.value.charAt(pos));
return pos;
}
}
Here is a code for a form:
<html>
<head>
<script src="numberFormat.js"></script>
</head>
<body>
<form name="form" action="<? $_SERVER['PHP_SELF'] ?>">
Test: <input type="text" name="text"
onkeypress="window.status=getCursorPosition2(text)"><br>
</form>
</body>
</html>