JavaScript实现验证登录账号密码为空功能
时间: 2023-07-12 07:32:37 浏览: 68
可以使用如下的JavaScript代码实现验证登录账号密码是否为空的功能:
```
function validateLoginForm() {
var username = document.forms["loginForm"]["username"].value;
var password = document.forms["loginForm"]["password"].value;
if (username == "" || password == "") {
alert("用户名和密码不能为空!");
return false;
}
return true;
}
```
上面的代码首先获取了登录表单中的用户名和密码,然后判断它们是否为空。如果有任何一个为空,就会弹出一个警告框提示用户“用户名和密码不能为空”,并且返回 false,阻止表单提交。如果用户名和密码都不为空,则返回 true,允许表单提交。在 HTML 中,可以将该函数绑定到表单的 onsubmit 事件上,例如:
```
<form name="loginForm" onsubmit="return validateLoginForm()">
<input type="text" name="username" placeholder="用户名">
<input type="password" name="password" placeholder="密码">
<button type="submit">登录</button>
</form>
```