prevent a form from being submitted while pressing enter key [duplicate]

ⅰ亾dé卋堺 提交于 2019-12-12 12:37:28

问题


how can we prevent a form from being submitted while pressing enter key.

Actually I have a text box and on entering a value on that textbox and clicking enter the textbox2 will get focused.

By default on clicking the enter button the form will get submitted. So I can not get the out put. I wrote return false on onclick event of the submit button then it works. So I would like to know how can we prevent a form submission while pressing enter.


回答1:


Without looking up the actual code, here's the basic theory behind how I'd do it:

Define an event handler on the document for a key being pressed to call a function.

If the key that triggered the event is the enter/return key, return false, otherwise return true.

EDIT: Looks like you already found the answer (as well as some code to do it), so my answer is somewhat unnecessary now.




回答2:


Writing 'onKeyPress' of the form like " { var key; if(window.event) key = window.event.keyCode; else key = e.which; //firefox return (key != 13); } " will work.




回答3:


what i do is add onsubmit="return false;" to the <form> tag. this will also disable the submit button however to create a working submit button use

<input type="button" value="Submit" onclick="javascript:document.form.submit();" />



回答4:


This should work

<form onsubmit="return false;">
    //Form elements
</form>


来源:https://stackoverflow.com/questions/6291348/prevent-a-form-from-being-submitted-while-pressing-enter-key

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