Form验证提交的两类写法形式:
<form id="form1" method="post" action="/DealWithForm1/">
<table>
<tr>
<td>first_name:</td>
<td><input name="firstname" type="text" id="firstname" /></td>
<td><label id="firstnameLabel"></label></td>
</tr>
<tr>
<td>last_name:</td>
<td><input name="lastname" type="text" id="lastname" /></td>
<td><label id="lastnameLabel"></label></td>
</tr>
</table>
<hr width="40%" align="left" />
<button type="submit">提交</button>
<button type="button" onclick="resetForm();">取消</button>
</form>
1.form的submit事件
(1.1) form绑定submit事件
将验证处理写在submit事件中
$(document).ready(function(){
$("#form1").bind("submit", function(){
var txt_firstname = $.trim($("#firstname").val());
var txt_lastname = $.trim($("#lastname").val());
$("#firstnameLabel").text("");
$("#lastnameLabel").text("");
var isSuccess = 1;
if(txt_firstname.length == 0){
$("#firstnameLabel").text("firstname不能为空!");
$("#firstnameLabel").css({"color":"red"});
isSuccess = 0;
}
if(txt_lastname.length == 0){
$("#lastnameLabel").text("lastname不能为空!")
$("#lastnameLabel").css({"color":"red"});
isSuccess = 0;
}
if(isSuccess == 0){
return false;
}
}); // end-submit
});
// 清空表单所有数据
function resetForm()
{
$("#firstname").value("");
$("#lastname").value("");
$("#firstnameLabel").text("");
$("#lastnameLabel").text("");
}
(1.2) 将验证处理写在页面form的onsubmit属性中
<form id="form1" method="post" action="/DealWithForm1/" onsubmit="return check()">
2.用按钮控制form提交
(2.1)submit按钮控件点击事件验证提交
<button type="submit" onclick="return check()">提交</button>
(2.2)button按钮点击事件验证提交
验证后要获取form调用其submit方法
<form action="login.do?act=login" name="myform" method="post">
<input type="button" value="提交" onclick="checkAndSubmit(this.form)"/>
JS代码:
function checkAndSubmit(form) {
if(form.userId.value=='') {
alert("请输入用户帐号!");
form.userId.focus();
return false;
}
if(form.password.value==''){
alert("请输入登录密码!");
form.password.focus();
return false;
}
document.myform.submit();
}