表单提交如果为空则获取焦点

快乐打工仔 分类:实例代码

本章节分享一段代码实例,它实现了点击提交按钮,如果表单中有相关元素为空的话,那么就此元素就会获取焦点。代码实例如下:

<!doctype html>
<html>
<head> 
<meta charset="utf-8">
<meta name="author" content="http://www.pipipi.net/" />
<title>前端教程网</title>
<script>
function func() {
  if (document.forms[0].elements[0].value.length == 0) {
    alert("姓名不可以为空");
    document.forms[0].elements[0].focus();
    return false;
  }
  else if (document.forms[0].elements[1].value.length == 0) {
    alert("密码不可以为空");
    document.forms[0].elements[1].focus();
    return false;
  }
  else { return true; }
}
window.onload = function () {
  document.forms[0].onsubmit = func;
}
</script>
</head>
<body>
<form action="antzone.php" method="post" name="myform">
  用户名<input type="text" name="name">
    密码<input type="password" name="password">
  <input type="submit" value="提交">
</form>
</body>
</html>

表单提交如果为空则获取焦点,这样的场景在实际项目中还是用的比较多的,关于表单提交如果为空则获取焦点就介绍到这了。

表单提交如果为空则获取焦点属于前端实例代码,有关更多实例代码大家可以查看

回复

我来回复
  • 暂无回复内容