I\'m trying to run a method when the enter key has been pressed. This method is already being used by a button. Basically, when the user fills in a text field and clicks a s
You can bind a keypress
event to the document and trigger()
the handler on your button.
$(document).bind('keypress', function(e){
if(e.which === 13) { // return
$('#buttonid').trigger('click');
}
});
This would fire whenever you press the return key on your site. You probably want it only to happen if someone uses return
in your input form. You would just need to change the selector
from document
to any kind of selector that matches your control.
Ref.: .trigger()
var ENTER_KEY = 13;
var user_key;
$(document).on('keydown', function(e){
user_key = e.keyCode || e.which
if(user_key === ENTER_KEY) {
document.querySelector("#button").click();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="button" onclick="console.log('button pressed')">button</button>
$(".input_loginform").keypress(function(e){
if (e.which == 13){
e.preventDefault();
alert("User pressed 'Enter' in a text input. sender form #"+this.form.id);
postlogin("#"+this.form.id);
}
});
$(document).keydown(function(e) {
// test for the enter key
if (e.keyCode == 13) {
// Do your function
myFunction();
}
});