0

I have an input.

<input name="inputName" id="inputId" value="Hello" />

Lets pretend that the cursor is after the e in hello, like so:

He|llo

How can I determine the position of the cursor within that string? Meaning, how can I make it tell me that the cursor is right after string{1} (or before string{2})?

Edit: Really though, my end goal is determine if the cursor is at the end of the string. I don't need to know if its in the middle. If it's at the end of the string, I am capturing arrow presses and will make it jump to the next form element. If it's at the beginning or middle, then I am not making that jump to the next form element. Jumping around on arrow presses works already, but it jumps irregardless of where the cursor is in the string.

phpmeh
  • 1,752
  • 2
  • 22
  • 41

2 Answers2

1

If you are using jQuery there is a plugin - fieldselection. It supports start/end, selected text, etc.

Bakudan
  • 19,134
  • 9
  • 53
  • 73
1

Here's a solution that does what you want without external dependencies: http://jsfiddle.net/imsky/ZH5JL/

Assuming fields #inputId and #secondField:

var field = document.getElementById("inputId");

function checkCaret(f) {
    if (caretPos(f) == field.value.length) {
        document.getElementById("secondField").focus();
    }
}

function caretPos(f) {
    if (f.createTextRange) {
        var r = document.selection.createRange().duplicate();
        r.moveEnd("character", f.value.length);
        return r.text == "" ? f.value.length : f.value.lastIndexOf(r.text)
    } else return f.selectionStart;
}

field.onkeyup = function() {
    checkCaret(this)
};
field.onkeydown = function() {
    checkCaret(this)
};
field.onfocus = function() {
    checkCaret(this)
};
imsky
  • 3,239
  • 17
  • 16
  • 1
    I found and used http://stackoverflow.com/questions/263743/how-to-get-cursor-position-in-textarea and it worked like a charm! Thanks for your help though! – phpmeh Dec 28 '11 at 01:50