我应该使用输入的onclick或表单的onsubmit事件来使用JavaScript验证表单字段吗?

问题描述:

我有一个简单的表单,其中包含我尝试使用JavaScript验证的字段。在表单中我有一个输入类型的提交。

I have a simple form with fields that I am trying to validate using JavaScript. In the form I have an input type of submit.

为了验证,我应该在表单的输入或提交上调用onclick事件的验证函数吗?是否有选择其中一个的含义?

For validation, should I call the validation function for onclick event on the input or onsubmit of the form? Is there any implication of choosing one over the other one?

onsubmit 只要表单即将提交,就会触发>。单击特定按钮时会触发
onclick

onsubmit is triggered whenever the form is about to be submitted.
onclick is triggered when the specific button is clicked.

可以通过在任何输入字段中按 enter 键来提交表单。这不会触发提交按钮的 onclick ,但会触发表单提交事件。因此,请使用 onsubmit

Forms can be submitted by hitting the enter key in any input field. This would not trigger the onclick of the submit button, but it would trigger the form submit event. As such, use onsubmit.