Form表单提交触发事件:onclick 与 onsubmit

form 表单提交一般都会要求对表单进行验证,验证不通过则不提交,可使用onclickonsubmit事件调用验证的方法进行处理。

  1. onsubmit提交事件,作用在表单上,提交表单前会触发;
  2. onclick是点击事件,作用在按钮或链接等各个标签对象里;
  3. onsubmitonclick也可同时使用,这时就存在优先级。
    onclick的优先级高于onsubmit。先触发 onclick 事件,返回true再触发 onsubmit 事件,onsubmit 返回 true 才提交表单。两者返回 false 都不会触发表单的提交。

示例代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

<script type="text/javascript" src="/static/js/jquery-1.11.0.min.js"></script>

</head>
<script type="text/javascript">
// $(function(){
// var forms = document.forms;
// alert(forms.length);
// });

function check(){
var username = $("#usernameId").val();
if(username == ""){
alert("form1:用户名不能为空");
return false
}else{
return true;
}
}

function validate(){
var account = $("#accountId").val();
var passwd = $("#passwdId").val();
if(account == "" || account.length == 0){
alert("form2: 用户名不能为空");
return false;
}
if(passwd == "" || passwd.length == 0){
alert("form2: 密码不为空");
}else{
return true;
}
}

function submitForm(){
var account = $("#accountId").val();
if(account == ""){
alert("submitForm 账号不能为空!")
return false;
}else{
this.document.forms[1].submit();
return true;
}
}

function jQuerySubmit(){
$("form").submit(function(e){
var account = $("#accountId").val();
if(account == ""){
alert("account不能为空")
return false;
}else{
return true;
}
});
}
</script>
<body>
<!-- form表单onsubmit触发事件:get/post -->
<h3>form表单button/input标签使用submit类型提交请求:get/post</h3>
<form action="/req/register" id="form0Id" method="post" onsubmit="return check()">
账号:<input type="text" name="username" id="usernameId"> <br>
密码:<input type="text" name="password" id="passwordId"> <br>
<button type="submit">button标签/onsubmit验证后提交表单</button>
<input type="submit" value="input标签/onsubmit验证后提交表单">
</form>

<!-- form表单onclick触发事件:get/post -->
<h3>form表单button标签onclick类型发送请求:get/post</h3>
<form action="/req/register" id="form1Id" method="post">
账号:<input type="text" name="account" id="accountId"> <br>
密码:<input type="text" name="passwd" id="passwdId"> <br>
<button type="submit" onclick="return validate()">button标签type属性submit提交表单,触发onclick点击事件来验证</button>
<br>
<button onclick="return submitForm()">form对象方法submit()提交表单,在方法里进行验证</button>
<br> <input type="submit" value="jQuery的submit()方法提交表单"
onclick="return jQuerySubmit()">
</form>
</body>
</html>

Form表单提交触发事件:onclick 与 onsubmit

http://blog.gxitsky.com/2018/01/27/jQuery-submit-onclick/

作者

光星

发布于

2018-01-27

更新于

2022-07-07

许可协议

评论

来发评论吧~
Powered By Valine
v1.4.16