使用JQuery实现登录的非空验证

操作说明:用户点击登录按钮后,若用户名为空,则弹出“用户名不能为空”的提示框,同时终止请求;若用户名不为空,密码为空,则弹出“密码不能为空”的提示框,同时终止请求。

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
    body{
        background-color: pink;
    }
</style>
<!-- base标签中的href属性可以让当前页面中的相对路径变为绝对路径 -->
<base href="http://localhost:8080/Web_Ex/">
<script type="text/javascript" src="script/jquery.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        /*
            text()方法:获取或设置成对出现的标签中的文本值
                对象.text():获取文本值
                对象.text("new value"):设置文本值
            html()方法与text()方法的唯一区别是html()方法可以解析html()标签
        */
        //给文本框绑定focus事件
        $("#username").focus(function(){
            //把显示错误信息的span标签里面的内容置空
            $("#msgSpan").html("");
        });
        /*
            val():获取或设置input标签的value属性值
                对象.val();    获取value属性值
                对象.val("new value");    设置value属性值
        */
        //给登录按钮绑定单击事件
        $("#subId").click(function(){
            //获取用户输入的用户名
            var username = $("#username").val();
            //判断用户名是否为空
            if(username == ""){
                alert("用户名不能为空");
                //取消默认行为
                return false;
            }
            //获取用户输入的密码用户名
            var password = $("#pwd").val();
            //判断密码是否为空
            if(password == ""){
                alert("密码不能为空");
                //取消默认行为
                return false;
            }
        });
    });
</script>
</head>
<body>
    <h1>欢迎登录</h1>
    <form action="LoginServlet" method="post">
        用户名称:<input type="text" name="username" id="username"/><br>
        用户密码:<input type="password" name="password" id="pwd"/><br>
        <input type="submit" value="登录" id="subId">
    </form>
</body>
</html>
原文地址:https://www.cnblogs.com/yanchaoyi/p/13444046.html