[英]Should I use the input's onclick or the form's onsubmit event to validate form fields using JavaScript?
I have a simple form with fields that I am trying to validate using JavaScript. 我有一个简单的表单,其中包含我尝试使用JavaScript验证的字段。 In the form I have an input type of submit.
在表单中我有一个输入类型的提交。
For validation, should I call the validation function for onclick event on the input or onsubmit of the form? 为了验证,我应该在表单的输入或提交上调用onclick事件的验证函数吗? Is there any implication of choosing one over the other one?
选择一个比另一个有任何影响吗?
onsubmit
is triggered whenever the form is about to be submitted. 只要提交表单,就会触发
onsubmit
。
onclick
is triggered when the specific button is clicked. 单击特定按钮时会触发
onclick
。
Forms can be submitted by hitting the enter key in any input field. 可以通过在任何输入字段中按Enter键来提交表单。 This would not trigger the
onclick
of the submit button, but it would trigger the form submit event. 这不会触发提交按钮的
onclick
,但会触发表单提交事件。 As such, use onsubmit
. 因此,请使用
onsubmit
。
Both onclick and onsubmit do the same thing. onclick和onsubmit都做同样的事情。 No matter you press enter on a text input element or press submit button , both are triggered.
无论您按文本输入元素上的Enter还是按提交按钮 ,都会触发。 If you use both onclick and onsubmit events, they are both executed respectively.
如果同时使用onclick和onsubmit事件,它们将分别执行。 And if You have more than one submit buttons in the form, the first submit button's onclick method is executed.
如果表单中有多个提交按钮,则会执行第一个提交按钮的onclick方法。 Tested on Internet Explorer, Firefox, Chrome and Opera.
在Internet Explorer,Firefox,Chrome和Opera上测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.