首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网站开发 > Web前端 >

[#0x0053] 遏止 form submit 的方法

2012-08-21 
[#0x0053] 阻止 form submit 的方法有两个地方可以可以阻止form submit,一是form onsubmit,而是form

[#0x0053] 阻止 form submit 的方法

有两个地方可以可以阻止form submit,一是<form onsubmit="">,而是<form>下的<input type="submit" onclick="">,只要这两个函数有一个是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;elsereturn 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>

?

热点排行