按下回车键时运行Jquery方法

时间:2022-09-20 14:42:34

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 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?

我正在尝试按下回车键时运行方法。该方法已被按钮使用。基本上,当用户填写文本字段并单击提交按钮时,他们会获得一个灯箱。我想要做的是运行相同的操作,但是当按下回车键时。我看过使用.keypress,但我只能找到form标签是标准html表单标签而不是asp.net表单标签的示例。我认为目前表单只响应页面上的.net控件,我不能用jquery方法覆盖它。有任何想法吗?

3 个解决方案

#1


5  

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.

只要您按网站上的返回键,就会触发此消息。如果有人在输入表单中使用return,您可能只希望它发生。您只需将选择器从文档更改为与您的控件匹配的任何类型的选择器。

Ref.: .trigger()

参考:.trigger()

#2


1  

$(document).keydown(function(e) {
   // test for the enter key
   if (e.keyCode == 13) {
      // Do your function
      myFunction();
   }
});

#3


1  

$(".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);
    }
});

#1


5  

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.

只要您按网站上的返回键,就会触发此消息。如果有人在输入表单中使用return,您可能只希望它发生。您只需将选择器从文档更改为与您的控件匹配的任何类型的选择器。

Ref.: .trigger()

参考:.trigger()

#2


1  

$(document).keydown(function(e) {
   // test for the enter key
   if (e.keyCode == 13) {
      // Do your function
      myFunction();
   }
});

#3


1  

$(".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);
    }
});