<form onSubmit="return check(this);"> 与 <input type="submit" onclick="return check(this);"/>

1. form 添加 onSubmit 属性,onSubmit="return check(this);"

<form action=" " name="form" onSubmit="return check(this);" method="POST">    
  <div class="name" >
    用户名</font> <input type="text" class="text" id="username" placeholder="用户名" name="username" tabindex="1">
    </div>
    <div class="pwd">
    密 码</font><input type="password" class="text" id="password" placeholder="密码" name="password" tabindex="2">
    </div>
    <div><input type="submit" class="submit" value="登录"/></div>
</form>

2. input 提交按钮,添加 onclick 属性,onclick="return check(this);"

<form action=" " name="form" method="POST">    
    <div class="name" >
        用户名</font> <input type="text" class="text" id="username" placeholder="用户名" name="username" tabindex="1">
    </div>
    <div class="pwd">
        密 码</font><input type="password" class="text" id="password" placeholder="密码" name="password" tabindex="2">
    </div>
    <div><input type="submit" onclick="return check(this);" class="submit" value="登录"/></div>
</form>

JavaScript 验证函数 function check() {}

<script type="text/javascript">
    function check() {
        var username = document.getElementById('username').value;
        var password = document.getElementById('password').value;
        if (username == '') {
            alert('用户名不能为空!');
            document.getElementById('username').focus();
            return false;
        }
        if (password == '') {
            alert('密码不能为空!');
            document.getElementById('password').focus();
            return false;
        }
        return true;
    }
    document.onkeydown = function (e) {// 键盘 F5 刷新页面
        e = e || window.event;
        if (e.keyCode == 116) {
            window.location.href = 'login.jsp';
            return false;// IE 9[10,11] 下 window.location.href 下不会失效
        }
    }
    window.onload = function() {
        document.getElementById('username').focus();
    }
</script>
原文地址:https://www.cnblogs.com/ikoo4396/p/6878303.html