JS阻止form表单提交

时间:2022-12-02 18:45:57

当做登陆页面时,JS判断用户名密码为空时需要阻止form表单提交。

<script type="text/javascript">
var a = true;
function validate(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if(username==""||password==""){
alert(
"Can't be empty");
a
= false;
return;
}
else{
a
=true;
}
}
function checkinput(){
return a;
}
</script>
<body>

<form method="post" action="hello.do" onsubmit="return checkinput();">
Username:
<input type="text" name="username" id="username"><br><br>
Password:
<input type="password" name="password" id="password"><br><br>
<center>
<input type="submit" value="Login" name="login" onclick="validate()">
</center>
</form>

</body>

点击submit后验证为空,form里的onsubmit获取到为false时就停止提交。