1. 程式人生 > >表單提交時js頁面不重新整理判斷輸入是否為空

表單提交時js頁面不重新整理判斷輸入是否為空

表單:給表單加上

onsubmit="return submitCheck();"
<form action="index.php" method="post" onsubmit="return submitCheck();">
		<table>
		<tr>
			<td>使用者名稱:</td>
			<td><input type="text" id="name" name="name" placeholder="請輸入使用者名稱" class="txt"></td>
		</tr>
		<tr>
			<td>密   碼:</td>
			<td><input type="password" id="pwd" name="pwd" placeholder="請輸入密碼" class="txt"></td>
		</tr>
		<tr>
			<td>驗證碼:</td>
			<td>
				<input type="text" id="yzm" name="yzm" size="10" placeholder="請輸入驗證碼" class="yzm">
                <img id="code" class="img_yzm" src="./public/common/yanzhengma.php" onclick="this.src+='?'"/> </td>
		</tr>
		<tr>
			<td colspan="2"><center><input type="radio" value="普通使用者" name="sf" checked="checked"/>普通使用者
			  <input type="radio" value="管理員" name="sf"/>管理員</center></td>
		</tr>
		<tr>
			<td colspan="2"><center>
				<input type="submit" name="login" value="登入" class="btn" id="btn1">
				<input type="reset" name="ret" value="重置" class="btn" id="btn2">
			</center></td>
		</tr>
		</table>
	</form>

js頁面不重新整理判斷輸入是否為空:

<script type="text/javascript">
// 表單元素提交時JS判斷輸入的值,為空時則不重新整理頁面返回,不為空跳轉並傳值到新頁面
 function submitCheck(){
 	var txt1 = document.getElementById("name");
 	var txt2 = document.getElementById("pwd");
    var txt3 = document.getElementById("yzm");
    if(txt1.value==""){
    	alert("請輸入使用者名稱!");
	    txt1.focus();
	    return false;  
    }else if(txt2.value==""){
    	alert("請輸入密碼!");
	    txt2.focus();
	    return false;  
    }else if(txt3.value==""){
    	alert("請輸入驗證碼!");
	    txt3.focus();
	    return false;  
    }
    return true;
  }
</script>