在做登录注册页面的时候,需要检测用户是否合法输入,其中重要的一条就是,验证表单的信息是否为空
下面以一个账号密码登录表单为例,说一下用Javascript的一个解决方案
JavaScript中的函数:
<script type="text/javascript"> function validate() { if(document.myform.username.value=="") { alert("用户名不能为空."); document.myform.username.focus(); return false ; } if(document.myform.password.value=="") { alert("密码不能为空."); document.myform.password.focus(); return false ; } return true; } </script>
Htnl表单
<form action="load" method="post" name="myform" id="myform" onsubmit="return validate()"> <input type="text" name="username" style="width:190px; height:26px;"/><br/> <input type="password" name="password" style="width:190px; height:26px; margin-top:12px;"/><br/> <input type="submit" value="登录" style="width:50px; height:30px; margin-top:8px;"/> </form>
获取username的另外方式:
var username=document.getElememntByID('username').value;
设置焦点的另外方式:
document.getElementById("username").focus();