以京东登录界面为例,点击登录后会依次检查用户名和密码是否为空等其他非法情况,检查函数是提交事件调用的,因此为form表单绑定onsubmit事件,在该事件中调用check函数对js元素进行校验,并返回其真值。
<script>
function check(){
var element = document.getElementById("username");
if(element.value==""){
alert("用户名不能为空");
return false;
}
element = document.getElementById("password")
if(element.value==""){
alert("密码不能为空");
return false;
}
return true;
}
function re(){
var element = document.getElementById("f1").reset();
}
</script>
<form id="f1" action="http://www.baidu.com" onsubmit="return check()" onreset="return re()">
<input id="username" placeholder="请输入用户名"/>
<input id="password" type="password" placeholder="请输入密码"/>
<input type="submit" value="登录"/>
<input type="reset" value="重置" />
</form>