onclick =“validateForm();返回false”?

时间:2018-01-07 04:59:49

标签: javascript html

我遇到了一些涉及提交按钮的代码,其onclick属性为:onclick =“validateForm(); return false”。例如:

<!DOCTYPE html>
<html>
<head>
<title>form</title>
<script>
function validateForm() {
    var name = document.forms["myForm"]["fname"].value; 
    if (name.trim() == "") {
        document.getElementById("demo").innerHTML = "Name must be filled out!";  
    }
    else
        document.myForm.submit();
}
</script>
</head>
<body>

<div id="demo" style="color:red"></div><br>
<form name="myForm" action="formHandler.jsp" method="post" target="_blank">
    Name: <input type="text" name="fname"> <br> 
    <input type="submit" value="Submit" onclick="validateForm();return false"> 
</form>

</body>
</html>

即使我在上面的示例中删除了return false,我也没有看到任何差异。只要输入了文本字段,return false就不会停止提交表单。那么,在document.myForm.submit()提交表单后立即使用“return false”的目的是什么?

2 个答案:

答案 0 :(得分:1)

表示document.myForm.submit()提交的表单不是,即错误情况。编写它的更好方法可能是让validateForm控制返回值:

function validateForm() {
    var name = document.forms["myForm"]["fname"].value; 
    if (name.trim() == "") {
        document.getElementById("demo").innerHTML = "Name must be filled out!";
        // Error; cancel the form submission
        return false;
    }

    // Just let the browser continue submitting; no need to .submit()
    return true;
}

<form name="myForm" action="formHandler.jsp" method="post" target="_blank"
      onsubmit="return validateForm()">
    Name: <input type="text" name="fname"> <br> 
    <input type="submit" value="Submit"> 
</form>

答案 1 :(得分:0)

检查工作示例:

function validateform(){  
var name=document.myform.name.value;  
var password=document.myform.password.value;  
  
if (name==null || name==""){  
  alert("Name can't be blank");  
  return false;  
}else if(password.length<6){  
  alert("Password must be at least 6 characters long.");  
  return false;  
  }  
}
  
  
<form name="myform" method="post" action="http://www.javatpoint.com/javascriptpages/valid.jsp" onsubmit="return validateform()" >  
Name: <input type="text" name="name"><br/>  
Password: <input type="password" name="password"><br/>  
<input type="submit" value="register">  
</form>