0

I would like to know if there are possible to know at which position of the input value is at when pressing a key.

Say I have a text field.

<input id="name" type="text">

And I want to to something if the right-arrow-key is pressed only if they are at the end of the string, and I want something else if the left-arrow-key is pressed if they are at the beginning of the input value. I want to be able to something like this:

$("#name").keyup( function(e) {
    if( e.which === 37 ) { // left
         if( isAtBeginningOfInputValue ) {
             // Do something
         }
    } else if( e.which === 39 ) { // right
         if( isAtEndOfInputValue ) {
             // Do something else
         }
    }
});

Is this possible?

user3065567
  • 71
  • 1
  • 1
  • 3
  • possible duplicate of [Get cursor position (in characters) within a text Input field](http://stackoverflow.com/questions/2897155/get-cursor-position-in-characters-within-a-text-input-field) – Amin Jafari Oct 01 '14 at 09:27

1 Answers1

0

the correct term for this blinking thin is caret

here you have a get function for textarea-elements

function GetCaretPosition (ctrl) {

    var CaretPos = 0;  
    // IE Support

    if (document.selection) {

    ctrl.focus ();

    var Sel = document.selection.createRange ();

    Sel.moveStart ('character', -ctrl.value.length);

    CaretPos = Sel.text.length;

    }

    // Firefox support

    else if (ctrl.selectionStart || ctrl.selectionStart == '0')

    CaretPos = ctrl.selectionStart;

    return (CaretPos);

}
john Smith
  • 17,409
  • 11
  • 76
  • 117