Run Jquery method when enter key is pressed

為{幸葍}努か 提交于 2019-12-01 04:16:33

问题


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?


回答1:


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()




回答2:


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



回答3:


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


来源:https://stackoverflow.com/questions/3716574/run-jquery-method-when-enter-key-is-pressed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!