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?

1

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.