Click here to Skip to main content
15,881,882 members
Please Sign up or sign in to vote.
3.00/5 (1 vote)
See more:
For a asp.net control below,
ASP.NET
<asp:TextBox ID="txtUser" runat="server" Font-Size="Small"  AutoPostBack="true" 
     TabIndex="2" Width="150px" 
     onkeypress="getFocus(event);" ></asp:TextBox>
...
function getFocus(event) {
   var chCode = ('charCode' in event) ? event.charCode : event.keyCode;
   //if (chcode == 9 || chcode = 13) {  // Tab or Enter
   //    document.getElementById("txtPassword").focus();
   //}
}

the keypress event fires if I click any key except for the TAB, BACK and ENTER keys. What's wrong in my code? Thanks.
Posted
Updated 26-Mar-15 5:02am
v2

1 solution

This is because these keys don't invoke this event at all; the event onkeypress is not invoked on all key presses, but mostly when a character is input (but also, say, Backspace considered as code point #8). You can use the events keydown, keyup, onblure (instead of Tab), on onfocus (instead of Tab):
http://www.w3schools.com/tags/ref_eventattributes.asp[^],
http://www.w3schools.com/tags/ev_onkeypress.asp[^].

—SA
 
Share this answer
 
v2
Comments
s yu 26-Mar-15 11:44am    
SA: Per your provided solution, I use onkeydown:
onkeydown="if(event.keyCode==13){event.keyCode=9; return event.keyCode}"
to solve this problem.
Thanks again.
Sergey Alexandrovich Kryukov 26-Mar-15 12:06pm    
Great. For Tab, you may want to consider onblur (typo fixed) and/or onfocus, depending on what you want to achieve.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900