---
title: "[#0x0053] 阻止 form submit 的方法"
author: "Aoyi"
date: "2011-10-18T21:21:16Z"
tags: ["HTML", "form", "submit"]
categories: ["Web前端"]
slug: "0x0053-form-submit"
draft: false
lastmod: "2011-10-18T21:23:41Z"
id: 1199623
url: "https://aoyi.iteye.com/blog/1199623"
---

有两个地方可以可以阻止form submit，一是&lt;form onsubmit=""&gt;，而是&lt;form&gt;下的&lt;input type="submit" onclick=""&gt;，只要这两个函数有一个是return false;，那么点击这个button并不会submit form。

 

具体的执行流程是这样的：

```
if (submitInput.onclick() == false) {
	// 不触发 form.onsubmit();
	// form 不提交;
} else {
	// 触发 form.onsubmit();
	if (form.onsubmit() == false) {
		// form 不提交
	} else {
		// 提交 form
	}
}
```

 

所以在这个两个函数里面可以加一些验证工作，同时，可以根据验证结果来判断是否提交form。

比如有：

```
var checkForm = function() {
	// 获取输入
	if (校验失败)
		return false；
	else
		return true；
}
```

 

然后把这个函数写到onsubmit或是onclick，也可以针对不同的button写不同的逻辑的校验函数，比如这样：

```
<html>
	<form onsubmit="return checkFormStep2();" method="post" action="/XXX.do">
		<input type="text" id="username">
		<input type="password" id="password">

		<input type="submit" onclick="return checkFormStep1();" value="go" />
	</form>
</html>
```

在点击时先执行checkFormStep1()，在form提交前再执行checkFormStep2()，两个都通过都return true了才提交

 

也可以针对“撤销”功能的按钮写一些类似清空输入的功能，再禁止它提交form，比如这样：

```
<html>
	<form method="post" action="/XXX.do">
		<input type="text" id="username">
		<input type="password" id="password">

		<input type="submit" onclick="return checkFormStep();" value="go" />
		<input type="submit" onclick="clearInput(); return false;" value="reset" />
	</form>
</html>
```