当任何输入为空时,我无法阻止表单提交。它没有出错,但也没有停止提交。我在表单提交输入中调用了该函数。它位于 onClick 调用下。
JS 文件
function stopSubmit(){
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
return false;
}
if (inType == "Select One"){
alert("Please select a frequency");
return false;
}
if (inAmount == ""){
alert("Please enter an amount");
return false;
}
else {
alert("Your form was submitted");
}
}
HTML 文件
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
最佳答案
编辑
使用 required
属性,您甚至不需要任何 JavaScript。请参阅演示 2。有关功能演示,请参阅此 PLUNKER
旧
在每个return false
之前添加e.preventDefault()
演示(由于 SO 安全措施而无法运行)
function stopSubmit(e) {
var inDay = document.getElementById(indate).value;
var inType = document.getElementById(intype).value;
var inAmount = document.getElementById(inamount).value;
if (inDay == "") {
alert("Please select a date");
e.preventDefault();
return false;
}
if (inType == "Select One") {
alert("Please select a frequency");
e.preventDefault();
return false;
}
if (inAmount == "") {
alert("Please enter an amount");
e.preventDefault();
return false;
} else {
alert("Your form was submitted");
}
}
<form>
<td>
<input type="submit" name="submitincome" value="submit" onclick="stopSubmit()">
</td>
</form>
演示 2 使用必需的属性
<!DOCTYPE html>
<html>
<head>
<style>
input {
display: block
}
</style>
</head>
<body>
<form id='inform' action='http://httpbin.org/post' method='post'>
<input id='indate' name='indate' required>
<input id='intype' name='intype' required>
<input id='inamount' name='inamount' required>
<input type="submit">
</form>
</body>
</html>
关于javascript - 无法阻止表单以空输入提交,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45900436/