1.當輸入用戶名和密碼爲空的時候,需要判斷。這時候就用到了校驗用戶名和密碼,這個需要在jsp的前端頁面寫;有兩種方法,一種是用submit提交。一種是用button提交。
方法一:用Submit提交
表單提交,在form標籤中增加onsubmit事件來判斷表單提交是否成功
<pre name="code" class="html"><form id="formid" name="myform" method='post' action='user_login_submit.action' <span style="font-family: Arial; font-size: 14px; line-height: 26px; color: rgb(255, 0, 0);">onsubmit = "return checkUser();</span><span style="color: rgb(51, 51, 51); font-family: Arial; font-size: 14px; line-height: 26px;">"</span> ">
<table width="100%" border="0">
<tr>
<td width="60" height="40" align="right">用戶名 </td>
<td><input type="text" value="" class="text2" name="username" id="userid"/></td>
</tr>
<tr>
<td width="60" height="40" align="right">密 碼 </td>
<td><input type="password" value="" class="text2" name="userpass" id="userpassid"/></td>
</tr>
<tr>
<td width="60" height="40" align="right"> </td>
<td>
<div class="c4">
<input type="submit" value="" class="btn2"/>
</div>
</td>
</tr>
</table>
</form>
<script>
window.onload = function () {
function checkUser() {
var result = document.getElementById("userid").value;
var password = document.getElementById("userpassid").value;
if (result == "") {
alert("用戶名不能爲空");
return false;
}
if (password == "") {
alert("密碼不能爲空");
return false;
} else {
return true;
}
}
}
</script>
方法二:用button提交
通過button按鈕來觸發表單提交事件οnclick="checkUser();",會忽略掉其他標籤中的屬性,比如form標籤中的onsubmit屬性就失效了。這時爲了進行表單驗證,可以將驗證代碼放在checkForm();方法中進行驗證。
<form id="formid" name="myform" method='post' action='user_login_submit.action' ">
<table width="100%" border="0">
<tr>
<td width="60" height="40" align="right">用戶名 </td>
<td><input type="text" value="" class="text2" name="username" id="userid"/></td>
</tr>
<tr>
<td width="60" height="40" align="right">密 碼 </td>
<td><input type="password" value="" class="text2" name="userpass" id="userpassid"/></td>
</tr>
<tr>
<td width="60" height="40" align="right"> </td>
<td>
<div class="c4">
<span style="background-color: rgb(255, 0, 0);"><input type="button" value="" class="btn2" onclick = "checkUser();" /></span>
</div>
</td>
</tr>
</table>
</form>
<script>
window.onload = function () {
function checkUser() {
var result = document.getElementById("userid").value;
var password = document.getElementById("userpassid").value;
if (result == "") {
alert("用戶名不能爲空");
return false;
}
if (password == "") {
alert("密碼不能爲空");
return false;
} else {
return true;
}
<span style="color:#ff0000;">document.getElementById("formid").submit();</span>
}
}
</script>
form表格的寫法,需要寫id<form id="formid" method = 'post' action = 'user_login_submit.action' >
button按鈕的寫法如下:
<input type="button" value="" class="btn2" onclick = "checkUser();" />