10

I'm trying to insert text into an html textbox when the user pushes buttons. This is a simple on screen numeric keypad. I have found many different scripts claiming to be able to find the current cursor position in a textbox cross-browser, but none work in IE (I'm using IE8). Is this just an IE8 defect? Is there a workaround?

It seems like there must be a definitive answer about this somewhere, but I have looked far and wide to no avail. To reiterate, how do I find the current cursor position in an html textbox?

Pete
  • 1,790
  • 2
  • 19
  • 31

3 Answers3

12

look here:

http://javascript.nwbox.com/cursor_position/

KM.
  • 101,727
  • 34
  • 178
  • 212
  • This is the best example of finding the cursor position that I've seen. You get the answer on this. There is one further complication. In the example, the focus in always in the textbox. When you use elements outside the textbox that respond to clicks in order to put text into the textbox, the textbox loses focus. This causes us to lose the current position in the textbox. --Pete – Pete Aug 17 '09 at 19:04
  • hide a field on the page: lastPosition and keep updating that field as they move around in the text box, when you lose focus, you can access this hidden field to see where the cusros was last. – KM. Aug 17 '09 at 19:17
2

Pete, you can also save the caret position by using an "onblur" event so you always know the previous caret position.

Diego Perini
  • 8,003
  • 1
  • 18
  • 9
0

The link in the selected answer is no longer working. I found out you need to use field.selectionStart.

Please check out this answer: https://stackoverflow.com/a/48150864/4031815

Aviv Dolev
  • 140
  • 3
  • 14