KeyUp/KeyDown keyCode Not Working on Password Fiel

2019-07-18 06:57发布

问题:

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.

回答1:

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>


回答2:

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)