I would like to detect whether the user has pressed Enter using jQuery.
How is this possible? Does it require a plugin?
EDIT: It looks like I need
As the keypress
event isn't covered by any official specification, the actual behavior encountered when using it may differ across browsers, browser versions, and platforms.
$(document).keydown(function(event) {
if (event.keyCode || event.which === 13) {
// Cancel the default action, if needed
event.preventDefault();
//call function, trigger events and everything tou want to dd . ex : Trigger the button element with a click
$("#btn").trigger('click');
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<button id="btn" onclick="console.log('Button Pressed.')"> </button>
I hope it would be useful!
The whole point of jQuery is that you don't have to worry about browser differences. I am pretty sure you can safely go with enter being 13 in all browsers. So with that in mind, you can do this:
$(document).on('keypress',function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
I think the simplest method would be using vanilla javacript:
document.onkeyup = function(event) {
if (event.key === 13){
alert("enter was pressed");
}
}
$(function(){
$('.modal-content').keypress(function(e){
debugger
var id = this.children[2].children[0].id;
if(e.which == 13) {
e.preventDefault();
$("#"+id).click();
}
})
});
I couldn't get the code posted by @Paolo Bergantino to work but when I changed it to $(document)
and e.which
instead of e.keyCode
then I found it to work faultlessly.
$(document).keypress(function(e) {
if(e.which == 13) {
alert('You pressed enter!');
}
});
Link to example on JS Bin
I spent sometime coming up with this solution i hope it helps someone.
$(document).ready(function(){
$('#loginforms').keypress(function(e) {
if (e.which == 13) {
//e.preventDefault();
alert('login pressed');
}
});
$('#signupforms').keypress(function(e) {
if (e.which == 13) {
//e.preventDefault();
alert('register');
}
});
});