0

I'm using jquery's function keypress for my input field

Now, let's say that I want to know when the user types a letter, if this is the first character in the field. I now use something like:

element.keypress(function(e){
    //...
    if(elementValue.length()==0){
        //Do something
    }
}

The problem is when the user selects the text that typed and then presses a key (lets say for the character 'A') that replaces it. Then this code returns the length of the old-(soon to be replaced) text.

I know that I could use keyup instead, but I think I need to stay with keypress because I have to do some checks for the pressed physical keys. (this answer really shows the difference between keyup and keypress in this case)

Any suggestions?

Community
  • 1
  • 1
Theodore K.
  • 5,058
  • 4
  • 30
  • 46
  • 1
    [_selectionStart_, _selectionEnd_](https://developer.mozilla.org/en/docs/Web/API/HTMLInputElement) (applies to `` and ` – Paul S. Apr 29 '14 at 10:51

1 Answers1

1

User Paul S. put me in the right direction...

That's what I have now and it works:

element.keypress(function(e){
    //...
    if(this.selectionStart==0){
        //Do something
    }
}

This way I detect when a key has been pressed while the caret was just at the beginning of the field.

Theodore K.
  • 5,058
  • 4
  • 30
  • 46