Saturday, May 11, 2024
 Popular · Latest · Hot · Upcoming
163
rated 0 times [  166] [ 3]  / answers: 1 / hits: 5269  / 10 Years ago, tue, april 29, 2014, 12:00:00

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?


More From » jquery

 Answers
41

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.


[#45680] Monday, April 28, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stefanicarolinat

Total Points: 145
Total Questions: 91
Total Answers: 93

Location: Cambodia
Member since Thu, Oct 7, 2021
3 Years ago
stefanicarolinat questions
Mon, Nov 15, 21, 00:00, 3 Years ago
Fri, Apr 16, 21, 00:00, 3 Years ago
Thu, Oct 15, 20, 00:00, 4 Years ago
Fri, Jul 17, 20, 00:00, 4 Years ago
;