示例1:
<body>
<form name="f1" id="f2" action="http://www.baidu.com" method="get" onsubmit="return check()">
<table>
<tr>
<td>Login</td>
<td><input type="text" name="username" id="username" ></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" id="password" ></td>
</tr>
<tr>
<td colspan="2" ><input type="submit" ></td>
</tr>
</table>
</form>
</body>
<script type="text/javascript">
//提交之前进行检查,如果return false,则不允许提交
function check(){
//根据ID获取值
var username=document.getElementById("username").value;
var password=document.getElementById("password").value;
if(username==""){
alert("用户名不能为空");
return false;
}
if(password==""){
alert("密码不能为空");
return false;
}
return true;
}
</script>
示例2:
<body>
<form name="f1" id="f2" action="http://www.baidu.com" method="get" onsubmit="return check()">
<table>
<tr>
<td>Login</td>
<td><input type="text" name="username" id="username" ></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="password" id="password" ></td>
</tr>
<tr>
<td colspan="2" ><input type="submit" ></td>
</tr>
</table>
</form>
</body>
<script type="text/javascript">
//提交之前进行检查,如果return false,则不允许提交
function check(){
if(f1.username==null||f1.username.value==""){
alert("用户名不能为空");
return false;
}
if(f1.password==null||f1.password.value==""){
alert("密码不能为空");
return false;
}
return true;
}
</script>
结果如下图