When binding to the keypress event in jQuery, there are two properties that can be used to identify the pressed key: keyCode and which.
You can find out which key was pressed using the keyCode or which property of the event object.
$('#searchbox input').bind('keypress', function(e) { var code = e.keyCode || e.which; if (code == 13) { //Enter keycode //Do something } });
Some browsers provide both keyCode and which, while others may only provide one. Generally, which is preferred in newer browsers, while keyCode is supported in older browsers.
To trigger a submit when the ENTER key is pressed, you can use the following code:
$('#searchbox input').bind('keypress', function(e) { var code = e.keyCode || e.which; if (code == 13) { $(this).closest('form').submit(); } });
The above is the detailed content of How Can I Determine the Pressed Key in a jQuery Keypress Event?. For more information, please follow other related articles on the PHP Chinese website!