简体   繁体   English

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

[英]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. onclickonsubmit都做同样的事情。 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.

相关问题 使用 onsubmit 验证表单 JavaScript - Validate form with JavaScript using onsubmit 是否可以在表单上以编程方式调用Javascript的onsubmit事件? - Is it possible to call Javascript's onsubmit event programmatically on a form? 未在表单上调用html / javascript onsubmit事件提交以验证表单 - html/javascript onsubmit event not called on form submit to validate form 如何在Javascript中验证表单的输入值 - How to validate a form's input value in Javascript JavaScript 在 PHP 之前没有响应(表单操作 = “php 文件” onsubmit = “表单的字段验证功能” - JavaScript not responsive before PHP (form action = "php file" onsubmit= " form’s fields validating function" 将javascript变量传递给表单/输入字段作为onsubmit href链接 - pass javascript variables to form/input fields as onsubmit href link 编辑文本输入时,如何在不使用表单的onSubmit处理程序的情况下按“ Enter”键执行特定的JavaScript操作? - When editing a text input, how do I do a specific JavaScript action on hitting “Enter” key without the form's onSubmit handler? 表单未触发javascript onsubmit事件 - Form not triggering javascript onsubmit event 以 javascript 形式注入 onsubmit 事件 - Inject onsubmit event in form javascript 使用onclick onsubmit w /按钮进行javascript表单验证 - javascript form validation using onclick onsubmit w/ button
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM