Run Jquery method when enter key is pressed
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 fi开发者_StackOverflowlls in a text field and clicks a submit button they get a lightbox. What I want to do is run this same action, but when the enter key has been pressed. Ive looked into using .keypress but I can only find examples where the form tag is a standard html form tag and not a asp.net form tag. I think at the moment the form is responding only to the .net controls on the page and I cant override this with the jquery method. Any ideas?
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()
$(document).keydown(function(e) {
// test for the enter key
if (e.keyCode == 13) {
// Do your function
myFunction();
}
});
$(".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);
}
});
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>
精彩评论