- 功能
- jQuery验证账号是否存在
- form表单提交判断,失焦判断
- 界面
- Ajax代码,验证用户rye1是否存在
function check_UserId() {$userId = $("#userId").val();$.post("checkUserId","userId=" + $userId,function (result) { // 异步访问servlet的数据if (result == "true") { // rye1 存在 禁用注册alert("账号存在!");document.getElementById("sub").disabled = true;}if (result == "false") {document.getElementById("sub").disabled = false;// 提交可用// $("#sub").disabled = false;}},"text");}
- index.jsp 页面
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><script type="" src = "scripts/jquery-1.8.3.min.js"></script><script type="text/javascript">function check_form() {var els = document.getElementsByTagName("input");for (var i = 0; i < els.length; i++) {if (typeof(els[i].getAttribute("onblur")) == "string" || typeof(els[i].getAttribute("onblur")) == "function") {if (!check_item(els[i])) {return false;}}}return true;}function check_item(obj) {var msgBox = obj.parentNode.getElementsByTagName("span")[0];var val = obj.value.trim();var name = obj.name;switch (name) {case "userId":if (val == "" || val == null) {msgBox.innerText = "填写用户名";return false;} else {// 验证账号是否存在check_UserId();} break;case "userPwd":if (val == "" || val == null) {msgBox.innerText = "填写密码";return false;} }return true;}function focus_item(obj) {var msgBox = obj.parentNode.getElementsByTagName("span")[0];msgBox.innerText = "";}</script></head><body><form action="registerServlet" method="post" onsubmit="return check_form()"><table><tr><td>userId: <input type="text" name="userId" id="userId" onfocus="focus_item(this)" onblur="check_item(this)"/><span></span></td><td>userPwd:<input type="password" name="userPwd" onfocus="focus_item(this)" onblur="check_item(this)"/><span></span></td></tr><tr><td><input type="submit" value="注册" id="sub" disabled="disabled"/></td><td><input type="reset" value="重置"/></td> </tr></table></form></body>
</html>
- 测试 注册按钮可用!