KeyUp/KeyDown keyCode Not Working on Password Fiel

2019-07-18 07:13发布

I have a simple form

<asp:TextBox ID="txtUsername" runat="server" CssClass="watermarkOn" TabIndex="1" />
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password" CssClass="watermarkOn" TabIndex="2" />
<asp:LinkButton ID="btnLogin" runat="server" CssClass="imgbtn_login" TabIndex="3" Text="login" onclick="btnLogin_Click" CausesValidation="false" />

With the following jQuery

$(document).ready(function () {
    $("#<%=txtUsername.ClientID %>").keydown(function (event) {
        if (event.keyCode == 13) {
            eval($("#<%=btnLogin.ClientID %>").attr('href'));
        }
    });
    $("#<%=txtPassword.ClientID %>").keydown(function (event) {

        if (event.keyCode == 13)
        {
            eval($("#<%=btnLogin.ClientID %>").attr('href'));
        }
    });
});

This works perfectly fine in FF, IE7, IE 9, Chrome, Safari....with one exception. Certain IE8 installations it works for the username box, but not for the password box. Does anyone know WHY this might be the case. I don't see any documentation around a difference in behavior for Password boxes.

Update

I've also tried keyup, as well as event.which, neither of which work either. Username box works fine, but the password box does not trigger like it should.

2条回答
SAY GOODBYE
2楼-- · 2019-07-18 07:39

If you use jQuery (you are :) ) Try (instead of keyCode) to use which:

jQuery normalises event.which depending on whether event.which, event.keyCode or event.charCode is supported by the browser:

if (event.which == 13) {

Here you can find more info: http://unixpapa.com/js/key.html (Look at: 3. Identifying Keys)

查看更多
Anthone
3楼-- · 2019-07-18 07:58

Attaching the keypress handler directly on the password field didn't work for me either in IE, but you can attach it to its parent though:

<script type="text/javascript">
$("#loginForm").keypress(function(e) {
    if (e.keyCode == $.ui.keyCode.ENTER) {
        // do your thing :)
    }
});
</script>

<form id="loginForm" action="...">
  <input type="text" id="username" value="" />
  <input type="password" id="password" />
  ...
</form>
查看更多
登录 后发表回答