一、使用submit按鈕,結合onsubmit事件實現
點擊提交表單的時候,觸發onsubmit的事件,這個事件會調用checkForm函數,該函數用於判斷用戶名是否爲空
當我們點擊提交表單時,將會觸發onsubmit事件
onsubmit裏是return checkForm,即調用checkForm函數
該函數用於判斷用戶名是否爲空
對於onsubmit,如果return的是false,就會取消提交的操作
如果return的是true,就會執行提交的操作,然後去找action裏面的login.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">>
<title>Hello</title>
<script type="text/javascript">
function checkForm() {
// body...
if( document.form1.username.value == ""){
window.alert("用戶名不能爲空");
return false;
}else{
window.alert("用戶名不爲空,驗證通過")
return true;
}
}
</script>>
</head>
<body>
<form name="form1" method="post" action="login.php" οnsubmit="return checkForm()">
用戶名:<input type="text" name="username">
密碼:<input type="password" name="userpwd">
<input type="submit" name="提交表單">
</form>
</body>
</html>
二、submit按鈕,結合onclick事件,實現表單的驗證和提交
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">>
<title>Hello</title>
<script type="text/javascript">
function checkForm() {
// body...
if( document.form1.username.value == ""){
window.alert("用戶名不能爲空");
return false;
}else{
window.alert("用戶名不爲空,驗證通過")
return true;
}
}
</script>>
</head>
<body>
<form name="form1" method="post" action="login.php" >
用戶名:<input type="text" name="username">
密碼:<input type="password" name="userpwd">
<input type="submit" name="提交表單" οnclick="checkForm()">
</form>
</body>
</html>
三、button普通按鈕,結合submit方法,實現表單驗證提交
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">>
<title>Hello</title>
<script type="text/javascript">
function checkForm() {
// body...
if( document.form1.username.value.length == 0){
window.alert("用戶名不能爲空");
}else if (document.form1.username.value.length < 5 || document.form1.username.value.length > 20){
window.alert("用戶名只能介於5到20個字符");
}else if (checkOtherChar(document.form1.username.value)){
window.alert("用戶名中含有特殊符號");
}else{
window.alert("驗證通過");
document.form1.submit();
}
}
</script>>
</head>
<body>
<form name="form1" method="post" action="login.php" >
用戶名:<input type="text" name="username">
密碼:<input type="password" name="userpwd">
<input type="button" name="提交表單" οnclick="checkForm()">
</form>
</body>
</html>