textfield caret problem

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>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,994
Messages
2,570,223
Members
46,812
Latest member
GracielaWa

Latest Threads

Top