With jQuery, how do I find out which key was pressed when I bind to the keypress event?
$(\'#searchbox input\').bind(\'keypress\', function(e) {});
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.
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
// 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');
}
});
The easiest way that I do is:
$("#element").keydown(function(event) {
if (event.keyCode == 13) {
localiza_cep(this.value);
}
});
According to Kilian's answer:
If only enter key-press is important:
<form action="javascript:alert('Enter');">
<input type=text value="press enter">
</form>
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){
}
});