jQuery Event Keypress: Which key was pressed?

后端 未结 24 1979
半阙折子戏
半阙折子戏 2020-11-21 16:48

With jQuery, how do I find out which key was pressed when I bind to the keypress event?

$(\'#searchbox input\').bind(\'keypress\', function(e) {});


        
相关标签:
24条回答
  • 2020-11-21 16:52

    Add hidden submit, not type hidden, just plain submit with style="display:none". Here is an example (removed unnecessary attributes from code).

    <form>
      <input type="text">
      <input type="submit" style="display:none">
    </form>
    

    it will accept enter key natively, no need for JavaScript, works in every browser.

    0 讨论(0)
  • 2020-11-21 16:53

    The event.keyCode and event.which are depracated. See @Gibolt answer above or check documentation: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

    event.key should be used instead

    keypress event is depracated as well: https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event

    0 讨论(0)
  • 2020-11-21 16:54
     // in jquery source code...
     if (!event.which && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode)) {
         event.which = event.charCode || event.keyCode;
     }
    
     // So you have just to use
     $('#searchbox input').bind('keypress', function(e) {
         if (e.which === 13) {
             alert('ENTER WAS PRESSED');
         }
     });
    
    0 讨论(0)
  • 2020-11-21 16:54

    The easiest way that I do is:

    $("#element").keydown(function(event) {
        if (event.keyCode == 13) {
            localiza_cep(this.value);
        }
    });
    
    0 讨论(0)
  • 2020-11-21 16:55

    According to Kilian's answer:

    If only enter key-press is important:

    <form action="javascript:alert('Enter');">
    <input type=text value="press enter">
    </form>
    
    0 讨论(0)
  • 2020-11-21 16:57

    Some browsers use keyCode, others use which. If you're using jQuery, you can reliably use which as jQuery standardizes things. Actually,

    $('#searchbox input').bind('keypress', function(e) {
        if(e.keyCode==13){
    
        }
    });
    
    0 讨论(0)
提交回复
热议问题