您必须返回 false 才能使页面不离开。
function validateForm()
{
var warnmsg = checkNames();
document.getElementById("row1").innerHTML = warnmsg;
return !warnmsg.length >0;//if there is a warning message, return false
}
然后以您的形式:
onsubmit="return validateForm()"
这是我的测试页面
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
function validateForm()
{
var warnmsg = checkNames();
document.getElementById("row1").innerHTML = warnmsg;
return !warnmsg.length >0;
}
function checkNames()
{
var fname = document.getElementById("fname");
if (fname.value.length==0)
return "Cannot be left blank";
else
return "";
}
</script>
</head>
<body>
<form onsubmit="return validateForm()">
<p id="row1"></p>
<input type="text" id="fname" />
<input type="submit" />
</form>
</body>
</html>