admin管理员组

文章数量:1419192

$("#username,#password").keypress(function(e)
    {
        //alert('');
        if(e.keyCode == 13)
        {
            signIn();
        }
    });

The keypress event not calling if the enter button is pressed.

$("#username,#password").keypress(function(e)
    {
        //alert('');
        if(e.keyCode == 13)
        {
            signIn();
        }
    });

The keypress event not calling if the enter button is pressed.

Share Improve this question edited Oct 22, 2012 at 12:10 GordonM 31.8k17 gold badges93 silver badges132 bronze badges asked Oct 22, 2012 at 12:09 NiDZNiDZ 932 silver badges7 bronze badges 2
  • 1 do the selected elements exist when code is run? If not use on() to delegate handler. If they exist..is code wrapped in document.ready – charlietfl Commented Oct 22, 2012 at 12:13
  • Any specific browser? Seems to be working here – user1726343 Commented Oct 22, 2012 at 12:13
Add a ment  | 

5 Answers 5

Reset to default 4

Try using keyUp event.

Live Demo

$("#username,#password").keyup(function(e){
        //alert('');
        if(e.keyCode == 13)
        {
            signIn();
        }
});

This is also working with keypress

Live Demo

$("#txt1").keypress(function(e) {

    if (e.keyCode == 13) {
        //signIn();
        alert("keypress");
    }
});​

Key down is more appropriate:

$("#username,#password").keydown(function(e){
        if(e.keyCode == 13)
        {
            signIn();
        }
});    
  1. Use e.which instead of e.keyCode because this is what jQuery guarantees to be on event
  2. Try e.preventDefault(), because without it (if they are in a form) the form submits
  3. Maybe the best would be listening on form's submit event

Are you sure it's not the signIn (); function that's faulty? Because this seems to work just fine; http://jsfiddle/vDkBs/1/

Use keypress and which statement:

$("#username,#password").keypress(function(e) {
    if (e.which == 13) {
        //call here your function
    }
});

本文标签: javascriptJquery key press event not triggered on enterStack Overflow