Enter key with multiple forms on a website

隐身守侯 提交于 2019-12-08 02:34:29

问题


I have a website with 2 forms. One for search and another for the login. When I use the enter key to submit, the search is always called because it is the first form on the page.

What I want to do is program the enter key to click a certain button when a certain textbox has focus.

I'm using asp:textbox and asp:button for my login form.


回答1:


Create a global variable which tracks what form is in focus:

<script> var currentForm = document.forms[0];</script>
<form ...><input onfocus="currentForm = this.form;"/></form>
<form ...><input onfocus="currentForm = this.form;"/></form>

Attach a keyboard handler to the window, look for the Enter key, then when it's hit submit the form that's being focused:

 function globalKeyPressed(event) {
   if (event.keyCode == ENTER) { // This is pseudo-code, check how to really do it
     currentForm.submit();
   }
 }



回答2:


If you are using asp.net webforms, then you can make use of the Panel control. The Panel control has a DefaultButton property which you set to the ID of an asp.net button control. When any control within that panel gains focus, the default button will be the referenced button.




回答3:


This worked perfectly:

$('form[name=yourformname]').submit(function(){...});



来源:https://stackoverflow.com/questions/3022697/enter-key-with-multiple-forms-on-a-website

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